repo_name
stringlengths
6
130
hexsha
list
file_path
list
code
list
apis
list
bombaci-vsc/sarpy
[ "3e31e9d7fca77612b60f2507f6f7068d1660a3e2" ]
[ "sarpy/io/complex/other_nitf.py" ]
[ "\"\"\"\nWork in progress for reading some other kind of complex NITF.\n\"\"\"\n\n__classification__ = \"UNCLASSIFIED\"\n__author__ = \"Thomas McCullough\"\n\nimport logging\nfrom typing import Union\n\nfrom datetime import datetime\nimport numpy\nfrom scipy.constants import foot\n\nfrom sarpy.compliance import string_types\n\nfrom sarpy.geometry.geocoords import geodetic_to_ecf, ned_to_ecf\nfrom sarpy.geometry.latlon import num as lat_lon_parser\n\nfrom sarpy.io.general.base import SarpyIOError\nfrom sarpy.io.general.nitf import extract_image_corners, NITFDetails, NITFReader\nfrom sarpy.io.general.nitf_elements.security import NITFSecurityTags\nfrom sarpy.io.general.nitf_elements.image import ImageSegmentHeader, ImageSegmentHeader0\nfrom sarpy.io.general.nitf_elements.nitf_head import NITFHeader, NITFHeader0\nfrom sarpy.io.general.nitf_elements.base import TREList\nfrom sarpy.io.general.nitf_elements.tres.unclass.CMETAA import CMETAA\nfrom sarpy.io.general.utils import is_file_like\n\nfrom sarpy.io.complex.base import SICDTypeReader\nfrom sarpy.io.complex.sicd_elements.SICD import SICDType\nfrom sarpy.io.complex.sicd_elements.CollectionInfo import CollectionInfoType\nfrom sarpy.io.complex.sicd_elements.ImageData import ImageDataType\nfrom sarpy.io.complex.sicd_elements.GeoData import GeoDataType, SCPType\nfrom sarpy.io.complex.sicd_elements.Grid import GridType, DirParamType, WgtTypeType\nfrom sarpy.io.complex.sicd_elements.Timeline import TimelineType, IPPSetType\nfrom sarpy.io.complex.sicd_elements.RadarCollection import RadarCollectionType, \\\n TxFrequencyType, WaveformParametersType, ChanParametersType\nfrom sarpy.io.complex.sicd_elements.SCPCOA import SCPCOAType\nfrom sarpy.io.complex.sicd_elements.ImageFormation import ImageFormationType, TxFrequencyProcType\nfrom sarpy.io.complex.sicd_elements.ImageCreation import ImageCreationType\nfrom sarpy.io.complex.sicd_elements.PFA import PFAType\n\nlogger = logging.getLogger(__name__)\n\n# NB: DO NOT implement is_a() here. This will explicitly happen after other readers\n\ndef final_attempt(file_name):\n \"\"\"\n Contingency check to open for some other complex NITF type file.\n Returns a reader instance, if so.\n\n Parameters\n ----------\n file_name : str|BinaryIO\n the file_name to check\n\n Returns\n -------\n ComplexNITFReader|None\n \"\"\"\n\n if is_file_like(file_name):\n return None\n\n try:\n nitf_details = ComplexNITFDetails(file_name)\n logger.info('File {} is determined to be some other format complex NITF.')\n return ComplexNITFReader(nitf_details)\n except (SarpyIOError, ValueError):\n return None\n\n\n########\n# Define sicd structure from image sub-header information\n\ndef extract_sicd(img_header, symmetry, nitf_header=None):\n \"\"\"\n Extract the best available SICD structure from relevant nitf header structures.\n\n Parameters\n ----------\n img_header : ImageSegmentHeader|ImageSegmentHeader0\n symmetry : tuple\n nitf_header : None|NITFHeader|NITFHeader0\n\n Returns\n -------\n SICDType\n \"\"\"\n\n def get_collection_info():\n # type: () -> CollectionInfoType\n isorce = img_header.ISORCE.strip()\n collector_name = None if len(isorce) < 1 else isorce\n\n iid2 = img_header.IID2.strip()\n core_name = img_header.IID1.strip() if len(iid2) < 1 else iid2\n\n class_str = img_header.Security.CLAS\n if class_str == 'T':\n classification = 'TOPSECRET'\n elif class_str == 'S':\n classification = 'SECRET'\n elif class_str == 'C':\n classification = 'CONFIDENTIAL'\n elif class_str == 'U':\n classification = 'UNCLASSIFIED'\n else:\n classification = ''\n ctlh = img_header.Security.CTLH.strip()\n if len(ctlh) < 1:\n classification += '//' + ctlh\n code = img_header.Security.CODE.strip()\n if len(code) < 1:\n classification += '//' + code\n\n return CollectionInfoType(\n CollectorName=collector_name,\n CoreName=core_name,\n Classification=classification)\n\n def get_image_data():\n # type: () -> ImageDataType\n pvtype = img_header.PVTYPE\n if pvtype == 'C':\n if img_header.NBPP != 64:\n logger.warning(\n 'This NITF has complex bands that are not 64-bit.\\n\\t'\n 'This is not currently supported.')\n pixel_type = 'RE32F_IM32F'\n elif pvtype == 'R':\n if img_header.NBPP == 64:\n logger.warning(\n 'The real/imaginary data in the NITF are stored as 64-bit floating point.\\n\\t'\n 'The closest Pixel Type, RE32F_IM32F, will be used,\\n\\t'\n 'but there may be overflow issues if converting this file.')\n pixel_type = 'RE32F_IM32F'\n elif pvtype == 'SI':\n pixel_type = 'RE16I_IM16I'\n else:\n raise ValueError('Got unhandled PVTYPE {}'.format(pvtype))\n\n if symmetry[2]:\n rows = img_header.NCOLS\n cols = img_header.NROWS\n else:\n rows = img_header.NROWS\n cols = img_header.NCOLS\n return ImageDataType(\n PixelType=pixel_type,\n NumRows=rows,\n NumCols=cols,\n FirstRow=0,\n FirstCol=0,\n FullImage=(rows, cols),\n SCPPixel=(0.5 * rows, 0.5 * cols))\n\n def append_country_code(cc):\n if len(cc) > 0:\n if the_sicd.CollectionInfo is None:\n the_sicd.CollectionInfo = CollectionInfoType(CountryCodes=[cc, ])\n elif the_sicd.CollectionInfo.CountryCodes is None:\n the_sicd.CollectionInfo.CountryCodes = [cc, ]\n elif cc not in the_sicd.CollectionInfo.CountryCodes:\n the_sicd.CollectionInfo.CountryCodes.append(cc)\n\n def set_image_corners(icps, override=False):\n if the_sicd.GeoData is None:\n the_sicd.GeoData = GeoDataType(ImageCorners=icps)\n elif the_sicd.GeoData.ImageCorners is None or override:\n the_sicd.GeoData.ImageCorners = icps\n\n def set_arp_position(arp_ecf, override=False):\n if the_sicd.SCPCOA is None:\n the_sicd.SCPCOA = SCPCOAType(ARPPos=arp_ecf)\n elif override:\n # prioritize this information first - it should be more reliable than other sources\n the_sicd.SCPCOA.ARPPos = arp_ecf\n\n def set_scp(scp_ecf, scp_pixel, override=False):\n def set_scppixel():\n if the_sicd.ImageData is None:\n the_sicd.ImageData = ImageDataType(SCPPixel=scp_pixel)\n else:\n the_sicd.ImageData.SCPPixel = scp_pixel\n if the_sicd.GeoData is None:\n the_sicd.GeoData = GeoDataType(SCP=SCPType(ECF=scp_ecf))\n set_scppixel()\n elif the_sicd.GeoData.SCP is None or override:\n the_sicd.GeoData.SCP = SCPType(ECF=scp_ecf)\n set_scppixel()\n\n def set_collect_start(collect_start, override=False):\n if the_sicd.Timeline is None:\n the_sicd.Timeline = TimelineType(CollectStart=collect_start)\n elif the_sicd.Timeline.CollectStart is None or override:\n the_sicd.Timeline.CollectStart = collect_start\n\n def set_uvects(row_unit, col_unit):\n if the_sicd.Grid is None:\n the_sicd.Grid = GridType(Row=DirParamType(UVectECF=row_unit),\n Col=DirParamType(UVectECF=col_unit))\n return\n\n if the_sicd.Grid.Row is None:\n the_sicd.Grid.Row = DirParamType(UVectECF=row_unit)\n elif the_sicd.Grid.Row.UVectECF is None:\n the_sicd.Grid.Row.UVectECF = row_unit\n\n if the_sicd.Grid.Col is None:\n the_sicd.Grid.Col = DirParamType(UVectECF=col_unit)\n elif the_sicd.Grid.Col.UVectECF is None:\n the_sicd.Grid.Col.UVectECF = col_unit\n\n def try_CMETAA():\n tre = None if tres is None else tres['CMETAA'] # type: CMETAA\n if tre is None:\n return\n\n cmetaa = tre.DATA\n\n if the_sicd.GeoData is None:\n the_sicd.GeoData = GeoDataType()\n if the_sicd.SCPCOA is None:\n the_sicd.SCPCOA = SCPCOAType()\n if the_sicd.Grid is None:\n the_sicd.Grid = GridType()\n if the_sicd.Timeline is None:\n the_sicd.Timeline = TimelineType()\n if the_sicd.RadarCollection is None:\n the_sicd.RadarCollection = RadarCollectionType()\n if the_sicd.ImageFormation is None:\n the_sicd.ImageFormation = ImageFormationType()\n\n the_sicd.SCPCOA.SCPTime = 0.5*float(cmetaa.WF_CDP)\n the_sicd.GeoData.SCP = SCPType(ECF=tre.get_scp())\n the_sicd.SCPCOA.ARPPos = tre.get_arp()\n\n the_sicd.SCPCOA.SideOfTrack = cmetaa.CG_LD.strip().upper()\n the_sicd.SCPCOA.SlantRange = float(cmetaa.CG_SRAC)\n the_sicd.SCPCOA.DopplerConeAng = float(cmetaa.CG_CAAC)\n the_sicd.SCPCOA.GrazeAng = float(cmetaa.CG_GAAC)\n the_sicd.SCPCOA.IncidenceAng = 90 - float(cmetaa.CG_GAAC)\n if hasattr(cmetaa, 'CG_TILT'):\n the_sicd.SCPCOA.TwistAng = float(cmetaa.CG_TILT)\n if hasattr(cmetaa, 'CG_SLOPE'):\n the_sicd.SCPCOA.SlopeAng = float(cmetaa.CG_SLOPE)\n\n the_sicd.ImageData.SCPPixel = [int(cmetaa.IF_DC_IS_COL), int(cmetaa.IF_DC_IS_ROW)]\n img_corners = tre.get_image_corners()\n if img_corners is not None:\n the_sicd.GeoData.ImageCorners = img_corners\n\n if cmetaa.CMPLX_SIGNAL_PLANE.upper() == 'S':\n the_sicd.Grid.ImagePlane = 'SLANT'\n elif cmetaa.CMPLX_SIGNAL_PLANE.upper() == 'G':\n the_sicd.Grid.ImagePlane = 'GROUND'\n else:\n logger.warning(\n 'Got unexpected CMPLX_SIGNAL_PLANE value {},\\n\\t'\n 'setting ImagePlane to SLANT'.format(cmetaa.CMPLX_SIGNAL_PLANE))\n\n the_sicd.Grid.Row = DirParamType(\n SS=float(cmetaa.IF_RSS),\n ImpRespWid=float(cmetaa.IF_RGRES),\n Sgn=1 if cmetaa.IF_RFFTS.strip() == '-' else -1, # opposite sign convention\n ImpRespBW=float(cmetaa.IF_RFFT_SAMP)/(float(cmetaa.IF_RSS)*float(cmetaa.IF_RFFT_TOT)))\n the_sicd.Grid.Col = DirParamType(\n SS=float(cmetaa.IF_AZSS),\n ImpRespWid=float(cmetaa.IF_AZRES),\n Sgn=1 if cmetaa.IF_AFFTS.strip() == '-' else -1, # opposite sign convention\n ImpRespBW=float(cmetaa.IF_AZFFT_SAMP)/(float(cmetaa.IF_AZSS)*float(cmetaa.IF_AZFFT_TOT)))\n cmplx_weight = cmetaa.CMPLX_WEIGHT.strip().upper()\n if cmplx_weight == 'UWT':\n the_sicd.Grid.Row.WgtType = WgtTypeType(WindowName='UNIFORM')\n the_sicd.Grid.Col.WgtType = WgtTypeType(WindowName='UNIFORM')\n elif cmplx_weight == 'HMW':\n the_sicd.Grid.Row.WgtType = WgtTypeType(WindowName='HAMMING')\n the_sicd.Grid.Col.WgtType = WgtTypeType(WindowName='HAMMING')\n elif cmplx_weight == 'HNW':\n the_sicd.Grid.Row.WgtType = WgtTypeType(WindowName='HANNING')\n the_sicd.Grid.Col.WgtType = WgtTypeType(WindowName='HANNING')\n elif cmplx_weight == 'TAY':\n the_sicd.Grid.Row.WgtType = WgtTypeType(\n WindowName='TAYLOR',\n Parameters={\n 'SLL': '-{0:d}'.format(int(cmetaa.CMPLX_RNG_SLL)),\n 'NBAR': '{0:d}'.format(int(cmetaa.CMPLX_RNG_TAY_NBAR))})\n the_sicd.Grid.Col.WgtType = WgtTypeType(\n WindowName='TAYLOR',\n Parameters={\n 'SLL': '-{0:d}'.format(int(cmetaa.CMPLX_AZ_SLL)),\n 'NBAR': '{0:d}'.format(int(cmetaa.CMPLX_AZ_TAY_NBAR))})\n else:\n logger.warning(\n 'Got unsupported CMPLX_WEIGHT value {}.\\n\\tThe resulting SICD will '\n 'not have valid weight array populated'.format(cmplx_weight))\n the_sicd.Grid.Row.define_weight_function()\n the_sicd.Grid.Col.define_weight_function()\n\n # noinspection PyBroadException\n try:\n date_str = cmetaa.T_UTC_YYYYMMMDD\n time_str = cmetaa.T_HHMMSSUTC\n date_time = '{}-{}-{}T{}:{}:{}'.format(\n date_str[:4], date_str[4:6], date_str[6:8],\n time_str[:2], time_str[2:4], time_str[4:6])\n the_sicd.Timeline.CollectStart = numpy.datetime64(date_time, 'us')\n except:\n pass\n the_sicd.Timeline.CollectDuration = float(cmetaa.WF_CDP)\n the_sicd.Timeline.IPP = [\n IPPSetType(TStart=0,\n TEnd=float(cmetaa.WF_CDP),\n IPPStart=0,\n IPPEnd=numpy.floor(float(cmetaa.WF_CDP)*float(cmetaa.WF_PRF)),\n IPPPoly=[0, float(cmetaa.WF_PRF)])]\n\n the_sicd.RadarCollection.TxFrequency = TxFrequencyType(\n Min=float(cmetaa.WF_SRTFR),\n Max=float(cmetaa.WF_ENDFR))\n the_sicd.RadarCollection.TxPolarization = cmetaa.POL_TR.upper()\n the_sicd.RadarCollection.Waveform = [WaveformParametersType(\n TxPulseLength=float(cmetaa.WF_WIDTH),\n TxRFBandwidth=float(cmetaa.WF_BW),\n TxFreqStart=float(cmetaa.WF_SRTFR),\n TxFMRate=float(cmetaa.WF_CHRPRT)*1e12)]\n tx_rcv_pol = '{}:{}'.format(cmetaa.POL_TR.upper(), cmetaa.POL_RE.upper())\n the_sicd.RadarCollection.RcvChannels = [\n ChanParametersType(TxRcvPolarization=tx_rcv_pol)]\n\n the_sicd.ImageFormation.TxRcvPolarizationProc = tx_rcv_pol\n if_process = cmetaa.IF_PROCESS.strip().upper()\n if if_process == 'PF':\n the_sicd.ImageFormation.ImageFormAlgo = 'PFA'\n scp_ecf = tre.get_scp()\n fpn_ned = numpy.array(\n [float(cmetaa.CG_FPNUV_X), float(cmetaa.CG_FPNUV_Y), float(cmetaa.CG_FPNUV_Z)], dtype='float64')\n ipn_ned = numpy.array(\n [float(cmetaa.CG_IDPNUVX), float(cmetaa.CG_IDPNUVY), float(cmetaa.CG_IDPNUVZ)], dtype='float64')\n fpn_ecf = ned_to_ecf(fpn_ned, scp_ecf, absolute_coords=False)\n ipn_ecf = ned_to_ecf(ipn_ned, scp_ecf, absolute_coords=False)\n the_sicd.PFA = PFAType(FPN=fpn_ecf, IPN=ipn_ecf)\n elif if_process in ['RM', 'CD']:\n the_sicd.ImageFormation.ImageFormAlgo = 'RMA'\n\n # the remainder of this is guesswork to define required fields\n the_sicd.ImageFormation.TStartProc = 0 # guess work\n the_sicd.ImageFormation.TEndProc = float(cmetaa.WF_CDP)\n the_sicd.ImageFormation.TxFrequencyProc = TxFrequencyProcType(\n MinProc=float(cmetaa.WF_SRTFR), MaxProc=float(cmetaa.WF_ENDFR))\n # all remaining guess work\n the_sicd.ImageFormation.STBeamComp = 'NO'\n the_sicd.ImageFormation.ImageBeamComp = 'SV' if cmetaa.IF_BEAM_COMP[0] == 'Y' else 'NO'\n the_sicd.ImageFormation.AzAutofocus = 'NO' if cmetaa.AF_TYPE[0] == 'N' else 'SV'\n the_sicd.ImageFormation.RgAutofocus = 'NO'\n\n def try_AIMIDA():\n tre = None if tres is None else tres['AIMIDA']\n if tre is None:\n return\n aimida = tre.DATA\n\n append_country_code(aimida.COUNTRY.strip())\n\n create_time = datetime.strptime(aimida.CREATION_DATE, '%d%b%y')\n if the_sicd.ImageCreation is None:\n the_sicd.ImageCreation = ImageCreationType(DateTime=create_time)\n elif the_sicd.ImageCreation.DateTime is None:\n the_sicd.ImageCreation.DateTime = create_time\n\n collect_start = datetime.strptime(aimida.MISSION_DATE+aimida.TIME, '%d%b%y%H%M')\n set_collect_start(collect_start, override=False)\n\n def try_AIMIDB():\n tre = None if tres is None else tres['AIMIDB']\n if tre is None:\n return\n aimidb = tre.DATA\n\n append_country_code(aimidb.COUNTRY.strip())\n\n if the_sicd.ImageFormation is not None and the_sicd.ImageFormation.SegmentIdentifier is None:\n the_sicd.ImageFormation.SegmentIdentifier = aimidb.CURRENT_SEGMENT.strip()\n\n date_str = aimidb.ACQUISITION_DATE\n collect_start = numpy.datetime64('{}-{}-{}T{}:{}:{}'.format(\n date_str[:4], date_str[4:6], date_str[6:8],\n date_str[8:10], date_str[10:12], date_str[12:14]), 'us')\n set_collect_start(collect_start, override=False)\n\n def try_ACFT():\n if tres is None:\n return\n tre = tres['ACFTA']\n if tre is None:\n tre = tres['ACFTB']\n if tre is None:\n return\n acft = tre.DATA\n\n sensor_id = acft.SENSOR_ID.strip()\n if len(sensor_id) > 1:\n if the_sicd.CollectionInfo is None:\n the_sicd.CollectionInfo = CollectionInfoType(CollectorName=sensor_id)\n elif the_sicd.CollectionInfo.CollectorName is None:\n the_sicd.CollectionInfo.CollectorName = sensor_id\n\n row_ss = float(acft.ROW_SPACING)\n col_ss = float(acft.COL_SPACING)\n\n if hasattr(acft, 'ROW_SPACING_UNITS') and acft.ROW_SPACING_UNITS.strip().lower() == 'f':\n row_ss *= foot\n if hasattr(acft, 'COL_SPACING_UNITS') and acft.COL_SPACING_UNITS.strip().lower() == 'f':\n col_ss *= foot\n\n # NB: these values are actually ground plane values, and should be\n # corrected to slant plane if possible\n if the_sicd.SCPCOA is not None:\n if the_sicd.SCPCOA.GrazeAng is not None:\n col_ss *= numpy.cos(numpy.deg2rad(the_sicd.SCPCOA.GrazeAng))\n if the_sicd.SCPCOA.TwistAng is not None:\n row_ss *= numpy.cos(numpy.deg2rad(the_sicd.SCPCOA.TwistAng))\n\n if the_sicd.Grid is None:\n the_sicd.Grid = GridType(Row=DirParamType(SS=row_ss), Col=DirParamType(SS=col_ss))\n return\n\n if the_sicd.Grid.Row is None:\n the_sicd.Grid.Row = DirParamType(SS=row_ss)\n elif the_sicd.Grid.Row.SS is None:\n the_sicd.Grid.Row.SS = row_ss\n\n if the_sicd.Grid.Col is None:\n the_sicd.Grid.Col = DirParamType(SS=col_ss)\n elif the_sicd.Grid.Col.SS is None:\n the_sicd.Grid.Col.SS = col_ss\n\n def try_BLOCKA():\n tre = None if tres is None else tres['BLOCKA']\n if tre is None:\n return\n blocka = tre.DATA\n\n icps = []\n for fld_name in ['FRFC_LOC', 'FRLC_LOC', 'LRLC_LOC', 'LRFC_LOC']:\n value = getattr(blocka, fld_name)\n # noinspection PyBroadException\n try:\n lat_val = float(value[:10])\n lon_val = float(value[10:21])\n except:\n lat_val = lat_lon_parser(value[:10])\n lon_val = lat_lon_parser(value[10:21])\n icps.append([lat_val, lon_val])\n set_image_corners(icps, override=False)\n\n def try_MPDSRA():\n def valid_array(arr):\n return numpy.all(numpy.isfinite(arr)) and numpy.any(arr != 0)\n\n tre = None if tres is None else tres['MPDSRA']\n if tre is None:\n return\n mpdsra = tre.DATA\n\n scp_ecf = foot*numpy.array(\n [float(mpdsra.ORO_X), float(mpdsra.ORO_Y), float(mpdsra.ORO_Z)], dtype='float64')\n if valid_array(scp_ecf):\n set_scp(scp_ecf, (int(mpdsra.ORP_COLUMN) - 1, int(mpdsra.ORP_ROW) - 1), override=False)\n\n arp_pos_ned = foot*numpy.array(\n [float(mpdsra.ARP_POS_N), float(mpdsra.ARP_POS_E), float(mpdsra.ARP_POS_D)], dtype='float64')\n arp_vel_ned = foot*numpy.array(\n [float(mpdsra.ARP_VEL_N), float(mpdsra.ARP_VEL_E), float(mpdsra.ARP_VEL_D)], dtype='float64')\n arp_acc_ned = foot*numpy.array(\n [float(mpdsra.ARP_ACC_N), float(mpdsra.ARP_ACC_E), float(mpdsra.ARP_ACC_D)], dtype='float64')\n arp_pos = ned_to_ecf(arp_pos_ned, scp_ecf, absolute_coords=True) if valid_array(arp_pos_ned) else None\n set_arp_position(arp_pos, override=False)\n\n arp_vel = ned_to_ecf(arp_vel_ned, scp_ecf, absolute_coords=False) if valid_array(arp_vel_ned) else None\n if the_sicd.SCPCOA.ARPVel is None:\n the_sicd.SCPCOA.ARPVel = arp_vel\n arp_acc = ned_to_ecf(arp_acc_ned, scp_ecf, absolute_coords=False) if valid_array(arp_acc_ned) else None\n if the_sicd.SCPCOA.ARPAcc is None:\n the_sicd.SCPCOA.ARPAcc = arp_acc\n\n if the_sicd.PFA is not None and the_sicd.PFA.FPN is None:\n # TODO: is this already in meters?\n fpn_ecf = numpy.array(\n [float(mpdsra.FOC_X), float(mpdsra.FOC_Y), float(mpdsra.FOC_Z)], dtype='float64') # *foot\n if valid_array(fpn_ecf):\n the_sicd.PFA.FPN = fpn_ecf\n\n def try_MENSRB():\n tre = None if tres is None else tres['MENSRB']\n if tre is None:\n return\n mensrb = tre.DATA\n\n arp_llh = numpy.array(\n [lat_lon_parser(mensrb.ACFT_LOC[:12]),\n lat_lon_parser(mensrb.ACFT_LOC[12:25]),\n foot*float(mensrb.ACFT_ALT)], dtype='float64')\n scp_llh = numpy.array(\n [lat_lon_parser(mensrb.RP_LOC[:12]),\n lat_lon_parser(mensrb.RP_LOC[12:25]),\n foot*float(mensrb.RP_ELV)], dtype='float64')\n # TODO: handle the conversion from msl to hae\n\n arp_ecf = geodetic_to_ecf(arp_llh)\n scp_ecf = geodetic_to_ecf(scp_llh)\n set_arp_position(arp_ecf, override=True)\n\n set_scp(scp_ecf, (int(mensrb.RP_COL)-1, int(mensrb.RP_ROW)-1), override=False)\n\n row_unit_ned = numpy.array(\n [float(mensrb.C_R_NC), float(mensrb.C_R_EC), float(mensrb.C_R_DC)], dtype='float64')\n col_unit_ned = numpy.array(\n [float(mensrb.C_AZ_NC), float(mensrb.C_AZ_EC), float(mensrb.C_AZ_DC)], dtype='float64')\n set_uvects(ned_to_ecf(row_unit_ned, scp_ecf, absolute_coords=False),\n ned_to_ecf(col_unit_ned, scp_ecf, absolute_coords=False))\n\n def try_MENSRA():\n tre = None if tres is None else tres['MENSRA']\n if tre is None:\n return\n mensra = tre.DATA\n\n arp_llh = numpy.array(\n [lat_lon_parser(mensra.ACFT_LOC[:10]),\n lat_lon_parser(mensra.ACFT_LOC[10:21]),\n foot*float(mensra.ACFT_ALT)], dtype='float64')\n scp_llh = numpy.array(\n [lat_lon_parser(mensra.CP_LOC[:10]),\n lat_lon_parser(mensra.CP_LOC[10:21]),\n foot*float(mensra.CP_ALT)], dtype='float64')\n # TODO: handle the conversion from msl to hae\n\n arp_ecf = geodetic_to_ecf(arp_llh)\n scp_ecf = geodetic_to_ecf(scp_llh)\n set_arp_position(arp_ecf, override=True)\n\n # TODO: is this already zero based?\n set_scp(geodetic_to_ecf(scp_llh), (int(mensra.CCRP_COL), int(mensra.CCRP_ROW)), override=False)\n\n row_unit_ned = numpy.array(\n [float(mensra.C_R_NC), float(mensra.C_R_EC), float(mensra.C_R_DC)], dtype='float64')\n col_unit_ned = numpy.array(\n [float(mensra.C_AZ_NC), float(mensra.C_AZ_EC), float(mensra.C_AZ_DC)], dtype='float64')\n set_uvects(ned_to_ecf(row_unit_ned, scp_ecf, absolute_coords=False),\n ned_to_ecf(col_unit_ned, scp_ecf, absolute_coords=False))\n\n def extract_corners():\n icps = extract_image_corners(img_header)\n if icps is None:\n return\n # TODO: include symmetry transform issue\n set_image_corners(icps, override=False)\n\n def extract_start():\n # noinspection PyBroadException\n try:\n date_str = img_header.IDATIM\n collect_start = numpy.datetime64('{}-{}-{}T{}:{}:{}'.format(\n date_str[:4], date_str[4:6], date_str[6:8],\n date_str[8:10], date_str[10:12], date_str[12:14]), 'us')\n except:\n return\n\n set_collect_start(collect_start, override=False)\n\n # noinspection PyUnresolvedReferences\n tres = None if img_header.ExtendedHeader.data is None \\\n else img_header.ExtendedHeader.data # type: Union[None, TREList]\n\n collection_info = get_collection_info()\n image_data = get_image_data()\n the_sicd = SICDType(\n CollectionInfo=collection_info,\n ImageData=image_data)\n # apply the various tres and associated logic\n # NB: this should generally be in order of preference\n try_CMETAA()\n try_AIMIDB()\n try_AIMIDA()\n try_ACFT()\n try_BLOCKA()\n try_MPDSRA()\n try_MENSRA()\n try_MENSRB()\n extract_corners()\n extract_start()\n return the_sicd\n\n\n# Helper methods for transforming data\n\ndef get_linear_magnitude_scaling(scale_factor):\n \"\"\"\n Get a linear magnitude scaling function, to correct magnitude.\n\n Parameters\n ----------\n scale_factor : float\n The scale factor, according to the definition given in STDI-0002.\n\n Returns\n -------\n callable\n \"\"\"\n\n def scaler(data):\n return data/scale_factor\n return scaler\n\n\ndef get_linear_power_scaling(scale_factor):\n \"\"\"\n Get a linear power scaling function, to derive correct magnitude.\n\n Parameters\n ----------\n scale_factor : float\n The scale factor, according to the definition given in STDI-0002.\n\n Returns\n -------\n callable\n \"\"\"\n\n def scaler(data):\n return numpy.sqrt(data/scale_factor)\n return scaler\n\n\ndef get_log_magnitude_scaling(scale_factor, db_per_step):\n \"\"\"\n Gets the log magnitude scaling function, to derive correct magnitude.\n\n Parameters\n ----------\n scale_factor : float\n The scale factor, according to the definition given in STDI-0002.\n db_per_step : float\n The db_per_step factor, according to the definiton given in STDI-0002\n\n Returns\n -------\n callable\n \"\"\"\n\n lin_scaler = get_linear_magnitude_scaling(scale_factor)\n\n def scaler(data):\n return lin_scaler(numpy.exp(0.05*numpy.log(10)*db_per_step*data))\n\n return scaler\n\n\ndef get_log_power_scaling(scale_factor, db_per_step):\n \"\"\"\n Gets the log power scaling function, to derive correct magnitude.\n\n Parameters\n ----------\n scale_factor : float\n The scale factor, according to the definition given in STDI-0002.\n db_per_step : float\n The db_per_step factor, according to the definiton given in STDI-0002\n\n Returns\n -------\n callable\n \"\"\"\n\n power_scaler = get_linear_power_scaling(scale_factor)\n def scaler(data):\n return power_scaler(numpy.exp(0.1*numpy.log(10)*db_per_step*data))\n\n return scaler\n\n\ndef get_linlog_magnitude_scaling(scale_factor, tipping_point):\n \"\"\"\n Gets the magnitude scaling function for the model which\n is initially linear, and then switches to logarithmic beyond a fixed\n tipping point.\n\n Parameters\n ----------\n scale_factor : float\n The scale factor, according to the definition given in STDI-0002.\n tipping_point : float\n The tipping point between the two models.\n\n Returns\n -------\n callable\n \"\"\"\n\n db_per_step = 20*numpy.log10(tipping_point)/tipping_point\n log_scaler = get_log_magnitude_scaling(scale_factor, db_per_step)\n\n def scaler(data):\n out = data/scale_factor\n above_tipping = (out > tipping_point)\n out[above_tipping] = log_scaler(data[above_tipping])\n return out\n return scaler\n\n\ndef get_qi_handler():\n \"\"\"\n Get the QI band handler.\n\n Returns\n -------\n callable\n \"\"\"\n\n # TODO: scaling function?\n\n def qi_handler(data):\n out = numpy.zeros((data.shape[0], data.shape[1], int(data.shape[2]/2)), dtype=numpy.complex64)\n out.real = data[:, :, 1::2]\n out.imag = data[:, :, 0::2]\n return out\n\n return qi_handler\n\n\ndef get_mp_handler(scaling_function=None):\n\n def mp_handler(data):\n out = numpy.zeros((data.shape[0], data.shape[1], int(data.shape[2]/2)), dtype=numpy.complex64)\n if data.dtype.name == 'uint8':\n theta = data[:, :, 1::2]*(2*numpy.pi/256)\n elif data.dtype.name == 'uint16':\n theta = data[:, :, 1::2] * (2 * numpy.pi / 65536)\n elif data.dtype.name == 'float32':\n theta = data[:, :, 1::2]\n else:\n raise ValueError('Got unsupported dtype {}'.format(data.dtype.name))\n\n amp = data[:, :, 0::2] if scaling_function is None else scaling_function(data[:, :, 0::2])\n out.real = amp*numpy.cos(theta)\n out.imag = amp*numpy.sin(theta)\n\n out.real = data[:, :, 1::2]\n out.imag = data[:, :, 0::2]\n return out\n return mp_handler\n\n\ndef get_pm_handler(scaling_function=None):\n\n def pm_handler(data):\n out = numpy.zeros((data.shape[0], data.shape[1], int(data.shape[2]/2)), dtype=numpy.complex64)\n if data.dtype.name == 'uint8':\n theta = data[:, :, 0::2]*(2*numpy.pi/256)\n elif data.dtype.name == 'uint16':\n theta = data[:, :, 0::2] * (2 * numpy.pi / 65536)\n elif data.dtype.name == 'float32':\n theta = data[:, :, 0::2]\n else:\n raise ValueError('Got unsupported dtype {}'.format(data.dtype.name))\n\n amp = data[:, :, 1::2] if scaling_function is None else scaling_function(data[:, :, 1::2])\n out.real = amp*numpy.cos(theta)\n out.imag = amp*numpy.sin(theta)\n\n out.real = data[:, :, 1::2]\n out.imag = data[:, :, 0::2]\n return out\n return pm_handler\n\n\ndef _extract_transform_data(img_header):\n \"\"\"\n Helper function for defining necessary transform_data definition for\n interpreting image segment data.\n\n Parameters\n ----------\n img_header : ImageSegmentHeader|ImageSegmentHeader0\n\n Returns\n -------\n None|str|callable\n \"\"\"\n\n if len(img_header.Bands) != 2:\n raise ValueError('Got unhandled case of {} image bands'.format(len(img_header.Bands)))\n\n isubcat_0 = img_header.Bands[0].ISUBCAT\n isubcat_1 = img_header.Bands[1].ISUBCAT\n # noinspection PyUnresolvedReferences\n tre = None if img_header.ExtendedHeader.data is None else \\\n img_header.ExtendedHeader.data['CMETAA'] # type: Union[None, CMETAA]\n if tre is None:\n if isubcat_0 == 'I' and isubcat_1 == 'Q':\n return 'COMPLEX'\n elif isubcat_0 == 'Q' and isubcat_1 == 'I':\n return get_qi_handler()\n elif isubcat_0 == 'M' and isubcat_1 == 'P':\n return get_mp_handler()\n elif isubcat_0 == 'P' and isubcat_1 == 'M':\n return get_pm_handler()\n return None\n else:\n cmetaa = tre.DATA\n if cmetaa.CMPLX_PHASE_SCALING_TYPE.strip() != 'NS':\n raise ValueError(\n 'Got unsupported CMPLX_PHASE_SCALING_TYPE {}'.format(\n cmetaa.CMPLX_PHASE_SCALING_TYPE))\n\n remap_type = cmetaa.CMPLX_MAG_REMAP_TYPE.strip()\n if remap_type == 'NS':\n if isubcat_0 == 'I' and isubcat_1 == 'Q':\n return 'COMPLEX'\n elif isubcat_0 == 'Q' and isubcat_1 == 'I':\n return get_qi_handler()\n else:\n raise ValueError(\n 'Got unexpected state where cmetaa.CMPLX_MAG_REMAP_TYPE is \"NS\", '\n 'but image_header.Band[0].ISUBCAT = \"{}\" and '\n 'image_header.Band[0].ISUBCAT = \"{}\"'.format(isubcat_0, isubcat_1))\n elif remap_type not in ['LINM', 'LINP', 'LOGM', 'LOGP', 'LLM']:\n raise ValueError('Got unsupported CMETAA.CMPLX_MAG_REMAP_TYPE {}'.format(remap_type))\n\n combined_subcat = isubcat_0+isubcat_1\n if combined_subcat not in ['MP', 'PM']:\n raise ValueError(\n 'Got unexpected state where cmetaa.CMPLX_MAG_REMAP_TYPE is \"{}\", '\n 'but image_header.Band[0].ISUBCAT = \"{}\" and '\n 'image_header.Band[0].ISUBCAT = \"{}\"'.format(remap_type, isubcat_0, isubcat_1))\n\n scale_factor = float(cmetaa.CMPLX_LIN_SCALE)\n if remap_type == 'LINM':\n scaling_function = get_linear_magnitude_scaling(scale_factor)\n elif remap_type == 'LINP':\n scaling_function = get_log_magnitude_scaling(scale_factor)\n elif remap_type == 'LOGM':\n # NB: there is nowhere in the CMETAA structure to define\n # the db_per_step value. Strangely, the use of this value is laid\n # out in the STDI-0002 standards document, which defines CMETAA\n # structure. We will generically use a value which maps the\n # max uint8 value to the max int16 value.\n db_per_step = 300*numpy.log(2)/255.0\n scaling_function = get_log_magnitude_scaling(scale_factor, db_per_step)\n elif remap_type == 'LOGP':\n db_per_step = 300*numpy.log(2)/255.0\n scaling_function = get_log_power_scaling(scale_factor, db_per_step)\n elif remap_type == 'LLM':\n scaling_function = get_linlog_magnitude_scaling(\n scale_factor, int(cmetaa.CMPLX_LINLOG_TP))\n else:\n raise ValueError('Got unhandled CMETAA.CMPLX_MAG_REMAP_TYPE {}'.format(remap_type))\n\n return get_mp_handler(scaling_function) if combined_subcat == 'MP' \\\n else get_pm_handler(scaling_function)\n\n\n######\n# The interpreter and reader objects\n\nclass ComplexNITFDetails(NITFDetails):\n \"\"\"\n Details object for NITF file containing complex data.\n \"\"\"\n\n __slots__ = ('_complex_segments', '_sicd_meta', '_symmetry', '_split_bands')\n\n def __init__(self, file_name, symmetry=(False, False, False), split_bands=True):\n \"\"\"\n\n Parameters\n ----------\n file_name : str\n file name for a NITF file containing a complex SICD\n symmetry : tuple\n split_bands : bool\n Split multiple complex bands into single bands?\n \"\"\"\n\n self._split_bands = split_bands\n self._symmetry = symmetry\n self._sicd_meta = None\n self._complex_segments = None\n super(ComplexNITFDetails, self).__init__(file_name)\n if self._nitf_header.ImageSegments.subhead_sizes.size == 0:\n raise SarpyIOError('There are no image segments defined.')\n self._find_complex_image_segments()\n if self._complex_segments is None:\n raise SarpyIOError('No complex valued (I/Q) image segments found in file {}'.format(file_name))\n\n @property\n def complex_segments(self):\n \"\"\"\n List[dict]: The image details for each relevant image segment.\n \"\"\"\n\n return self._complex_segments\n\n @property\n def sicd_meta(self):\n \"\"\"\n Tuple[SICDType]: The best inferred sicd structures.\n \"\"\"\n\n return self._sicd_meta\n\n def _find_complex_image_segments(self):\n \"\"\"\n Find complex image segments.\n\n Returns\n -------\n None\n \"\"\"\n\n def extract_band_details(index, image_header):\n # type: (int, Union[ImageSegmentHeader, ImageSegmentHeader0]) -> None\n\n # populate sicd_meta and complex_segments appropriately\n if image_header.ICAT.strip() not in ['SAR', 'SARIQ']:\n return\n\n if image_header.NBPP not in [8, 16, 32, 64]:\n return # this should be redundant with general NITF checking\n\n sicd = extract_sicd(img_header, self._symmetry)\n\n bands = len(image_header.Bands)\n if bands == 1:\n if image_header.PVTYPE != 'C':\n return # this is not a complex dataset - maybe we should warn?\n if image_header.NBPP == 32:\n logger.warning(\n 'File {} has image band at index {} of complex data type with 32 bits per pixel\\n\\t'\n '(real/imaginary components) consisting of 16-bit floating points.\\n\\t'\n 'This is experimentally supported assuming the data follows the\\n\\t'\n 'ieee standard for half precision floating point, i.e. 1 bit sign, 5 bits exponent,\\n\\t'\n 'and 10 bits significand/mantissa'.format(self.file_name, index))\n sicd_meta.append(sicd)\n complex_segments.append({\n 'index': index,\n 'raw_dtype': numpy.dtype('>f2'),\n 'raw_bands': 2,\n 'transform_data': 'COMPLEX',\n 'output_bands': 1,\n 'output_dtype': numpy.dtype('>c8')})\n elif image_header.NBPP == 64:\n sicd_meta.append(sicd)\n complex_segments.append({\n 'index': index,\n 'raw_dtype': numpy.dtype('>c8'),\n 'raw_bands': 1,\n 'transform_data': None,\n 'output_bands': 1,\n 'output_dtype': numpy.dtype('>c8')})\n elif image_header.NBPP == 128:\n sicd_meta.append(sicd)\n complex_segments.append({\n 'index': index,\n 'raw_dtype': numpy.dtype('>c16'),\n 'raw_bands': 1,\n 'transform_data': None,\n 'output_bands': 1,\n 'output_dtype': numpy.dtype('>c16')})\n else:\n logger.error(\n 'File {} has image band at index {} of complex type with bits per pixel value {}.\\n\\t'\n 'This is not currently supported and this band will be skipped.'.format(\n self.file_name, index, image_header.NBPP))\n return\n\n # do some general assignment for input datatype\n bpp = int(image_header.NBPP/8)\n pv_type = image_header.PVTYPE\n if pv_type == 'INT':\n raw_dtype = '>u{}'.format(bpp)\n elif pv_type == 'SI':\n raw_dtype = '>i{}'.format(bpp)\n elif pv_type == 'R':\n raw_dtype ='>f{}'.format(bpp)\n else:\n logger.warning(\n 'Got unhandled PVTYPE {} for image band {}\\n\\t'\n 'in file {}. Skipping'.format(pv_type, index, self.file_name))\n return\n\n if bands == 2:\n # this should be the most common by far\n transform_data = _extract_transform_data(image_header)\n if transform_data is not None:\n sicd_meta.append(sicd)\n complex_segments.append({\n 'index': index,\n 'raw_dtype': raw_dtype,\n 'raw_bands': 2,\n 'transform_data': transform_data,\n 'output_bands': 1,\n 'output_dtype': numpy.complex64})\n elif (bands % 2) == 0:\n # this is explicitly to support the somewhat unusual RCM NITF format\n cont = True\n for j in range(0, bands, 2):\n cont &= (image_header.Bands[j].ISUBCAT == 'I'\n and image_header.Bands[j+1].ISUBCAT == 'Q')\n if self._split_bands and bands > 2:\n for j in range(0, bands, 2):\n complex_segments.append({\n 'index': index,\n 'raw_dtype': raw_dtype,\n 'raw_bands': bands,\n 'transform_data': 'COMPLEX',\n 'output_bands': 1,\n 'output_dtype': numpy.complex64,\n 'limit_to_raw_bands': numpy.array([j, j+1], dtype='int32')})\n sicd_meta.append(sicd.copy())\n else:\n sicd_meta.append(sicd)\n complex_segments.append({\n 'index': index,\n 'raw_dtype': raw_dtype,\n 'raw_bands': bands,\n 'transform_data': 'COMPLEX',\n 'output_bands': int(bands/2),\n 'output_dtype': numpy.complex64})\n\n # ['raw_dtype', 'raw_bands', 'transform_data', 'output_bands', 'output_dtype', 'limit_to_raw_bands']\n if image_header.ICAT.strip() in ['SAR', 'SARIQ'] and ((bands % 2) == 0):\n # TODO: account for PVType == 'C' and ISUBCAT = 'M'/'P'\n cont = True\n for j in range(0, bands, 2):\n cont &= (image_header.Bands[j].ISUBCAT == 'I'\n and image_header.Bands[j+1].ISUBCAT == 'Q')\n return bands\n return 0\n\n sicd_meta = []\n complex_segments = []\n for i, img_header in enumerate(self.img_headers):\n extract_band_details(i, img_header)\n\n if len(sicd_meta) > 0:\n self._complex_segments = complex_segments\n self._sicd_meta = tuple(sicd_meta)\n\n\nclass ComplexNITFReader(NITFReader, SICDTypeReader):\n \"\"\"\n A reader for complex valued NITF elements, this should be explicitly tried AFTER\n the SICDReader.\n \"\"\"\n\n def __init__(self, nitf_details, symmetry=(False, False, False), split_bands=True):\n \"\"\"\n\n Parameters\n ----------\n nitf_details : str|ComplexNITFDetails\n symmetry : tuple\n Passed through to ComplexNITFDetails() in the event that `nitf_details` is a file name.\n split_bands : bool\n Passed through to ComplexNITFDetails() in the event that `nitf_details` is a file name.\n \"\"\"\n\n if isinstance(nitf_details, string_types):\n nitf_details = ComplexNITFDetails(nitf_details, symmetry=symmetry, split_bands=split_bands)\n if not isinstance(nitf_details, ComplexNITFDetails):\n raise TypeError('The input argument for ComplexNITFReader must be a filename or '\n 'ComplexNITFDetails object.')\n\n SICDTypeReader.__init__(self, nitf_details.sicd_meta)\n super(ComplexNITFReader, self).__init__(nitf_details, reader_type=\"SICD\", symmetry=symmetry)\n\n @property\n def nitf_details(self):\n # type: () -> ComplexNITFDetails\n \"\"\"\n ComplexNITFDetails: The NITF details object.\n \"\"\"\n\n # noinspection PyTypeChecker\n return self._nitf_details\n\n def get_nitf_dict(self):\n \"\"\"\n Populate a dictionary with the pertinent NITF header information. This\n is for use in more faithful preservation of NITF header information\n in copying or rewriting sicd files.\n\n Returns\n -------\n dict\n \"\"\"\n\n out = {}\n security = {}\n security_obj = self.nitf_details.nitf_header.Security\n # noinspection PyProtectedMember\n for field in NITFSecurityTags._ordering:\n value = getattr(security_obj, field).strip()\n if value != '':\n security[field] = value\n if len(security) > 0:\n out['Security'] = security\n\n out['OSTAID'] = self.nitf_details.nitf_header.OSTAID\n out['FTITLE'] = self.nitf_details.nitf_header.FTITLE\n return out\n\n def populate_nitf_information_into_sicd(self):\n \"\"\"\n Populate some pertinent NITF header information into the SICD structure.\n This provides more faithful copying or rewriting options.\n \"\"\"\n\n nitf_dict = self.get_nitf_dict()\n for sicd_meta in self._sicd_meta:\n sicd_meta.NITF = nitf_dict\n\n def depopulate_nitf_information(self):\n \"\"\"\n Eliminates the NITF information dict from the SICD structure.\n \"\"\"\n\n for sicd_meta in self._sicd_meta:\n sicd_meta.NITF = {}\n\n def _find_segments(self):\n return [[entry['index'], ] for entry in self.nitf_details.complex_segments]\n\n def _construct_chipper(self, segment, index):\n entry = self.nitf_details.complex_segments[index]\n if entry['index'] != segment[0]:\n raise ValueError('Got incompatible entries.')\n\n kwargs = {}\n for key in ['raw_dtype', 'raw_bands', 'transform_data', 'output_bands', 'output_dtype', 'limit_to_raw_bands']:\n if key in entry:\n kwargs[key] = entry[key]\n return self._define_chipper(entry['index'], **kwargs)\n" ]
[ [ "numpy.sin", "numpy.array", "numpy.log", "numpy.any", "numpy.sqrt", "numpy.cos", "numpy.deg2rad", "numpy.isfinite", "numpy.log10", "numpy.dtype", "numpy.datetime64" ] ]
JoyeBright/Deep-Learning
[ "ba62cc8b3cbeeacc11b69f52999aac2bd0d7f018" ]
[ "ActivationFunction.py" ]
[ "# Forward Propagation Algorithm By Using Activation Function\nimport numpy as np\n\n# Define rectified linear unit function\n\n\ndef relu(inp):\n out = max(0, inp)\n return out\n\n\ninput_data = np.array([2,3])\n\n# Using dictionary in order to save weights of hidden and output layer\nweights = { 'node0': np.array([1,1]),\n 'node1': np.array([-1,1]),\n 'output': np.array([2,-1])}\nnode0_input = (input_data * weights['node0']).sum()\nnode0_output = relu(node0_input)\n# Note: sum() is a built-in function which works as an iterator\nnode1_input = (input_data * weights['node1']).sum()\nnode1_output = relu(node1_input)\n\nhidden_layer_values = np.array([node0_output,node1_output])\nprint(\"Hidden layers values: %s\" % hidden_layer_values)\noutput = (hidden_layer_values * weights['output']).sum()\n\n# Written transaction because of the problem\n# Here we wanted to predict the number of the next year transaction based on two parameters or features\n# Like age or number of children and so on\nprint(\"Total # of Transactions:%d\" % output)\n\n# Note: without activation function, you would have predicted a negative number!\n\n" ]
[ [ "numpy.array" ] ]
ThomasDemaris/TheFinalFaceIt
[ "1c6dc575000bba02d847062b002c15e9409eaa50" ]
[ "trainDatabase.py" ]
[ "#!/usr/bin/env python\n\nimport os\nimport cv2\nimport sys\nimport shutil\nimport random\nimport operator\nimport sqlite3\nimport pickle\nimport numpy as np\n\n\"\"\"\nTrain and save the eigenvectors for a specified database.\n\nExample Call:\n $> python eigenfaces.py bdd_faces\n\"\"\"\nclass Eigenfaces(object): # *** COMMENTS ***\n faces_count = 0\n faces_dir = '.' # directory path to the faces database\n\n train_faces_count = 9 # number of faces used for training\n test_faces_count = 1 # number of faces used for testing\n\n l = 0\n m = 92 # number of columns of the image\n n = 112 # number of rows of the image\n mn = m * n # length of the column vector\n\n \"\"\"\n Initializing the Eigenfaces model.\n \"\"\"\n def __init__(self, _faces_dir = '.', _energy = 0.85):\n\n self.faces_dir = _faces_dir\n self.faces_count = len([f for f in os.listdir(self.faces_dir)]) - 1\n self.energy = _energy\n self.training_ids = [] # train image id's for every at&t face\n self.l = self.train_faces_count * self.faces_count # training images count\n \n L = np.empty(shape=(self.mn, self.l), dtype='float64') # each row of L represents one train image\n\n cur_img = 0\n for face_id in range(1, self.faces_count + 1):\n\n training_ids = random.sample(range(1, 11), self.train_faces_count) # the id's of the 6 random training images\n self.training_ids.append(training_ids) # remembering the training id's for later\n\n for training_id in training_ids:\n path_to_img = os.path.join(self.faces_dir,\n 's' + str(face_id), str(training_id) + '.pgm') # relative path\n\n img = cv2.imread(path_to_img, 0) # read a grayscale image\n img_col = np.array(img, dtype='float64').flatten() # flatten the 2d image into 1d\n\n L[:, cur_img] = img_col[:] # set the cur_img-th column to the current training image\n cur_img += 1\n\n self.mean_img_col = np.sum(L, axis=1) / self.l # get the mean of all images / over the rows of L\n\n for j in range(0, self.l): # subtract from all training images\n L[:, j] -= self.mean_img_col[:]\n\n C = np.matrix(L.transpose()) * np.matrix(L) # instead of computing the covariance matrix as\n C /= self.l # L*L^T, we set C = L^T*L, and end up with way\n # smaller and computentionally inexpensive one\n # we also need to divide by the number of training\n # images\n\n\n self.evalues, self.evectors = np.linalg.eig(C) # eigenvectors/values of the covariance matrix\n sort_indices = self.evalues.argsort()[::-1] # getting their correct order - decreasing\n self.evalues = self.evalues[sort_indices] # puttin the evalues in that order\n self.evectors = self.evectors[sort_indices] # same for the evectors\n\n evalues_sum = sum(self.evalues[:]) # include only the first k evectors/values so\n evalues_count = 0 # that they include approx. 85% of the energy\n evalues_energy = 0.0\n for evalue in self.evalues:\n evalues_count += 1\n evalues_energy += evalue / evalues_sum\n\n if evalues_energy >= self.energy:\n break\n\n self.evalues = self.evalues[0:evalues_count] # reduce the number of eigenvectors/values to consider\n self.evectors = self.evectors[0:evalues_count]\n\n self.evectors = self.evectors.transpose() # change eigenvectors from rows to columns\n self.evectors = L * self.evectors # left multiply to get the correct evectors\n norms = np.linalg.norm(self.evectors, axis=0) # find the norm of each eigenvector\n self.evectors = self.evectors / norms # normalize all eigenvectors\n\n self.W = self.evectors.transpose() * L # computing the weights\n\n\n \"\"\"\n Classify an image to one of the eigenfaces.\n \"\"\"\n def classify(self, path_to_img):\n img = cv2.imread(path_to_img, 0) # read as a grayscale image\n img_col = np.array(img, dtype='float64').flatten() # flatten the image\n img_col -= self.mean_img_col # subract the mean column\n img_col = np.reshape(img_col, (self.mn, 1)) # from row vector to col vector\n\n S = self.evectors.transpose() * img_col # projecting the normalized probe onto the\n # Eigenspace, to find out the weights\n\n diff = self.W - S # finding the min ||W_j - S||\n norms = np.linalg.norm(diff, axis=0)\n\n closest_face_id = np.argmin(norms) # the id [0..240) of the minerror face to the sample\n return (closest_face_id / self.train_faces_count) + 1 # return the faceid (1..40)\n\n \"\"\"\n Evaluate the model using the 4 test faces left\n from every different face in the database.\n \"\"\"\n def evaluate(self):\n print ('> Auto-evaluation of database')\n results_file = os.path.join('results', 'att_results.txt') # filename for writing the evaluating results in\n f = open(results_file, 'w') # the actual file\n\n test_count = self.test_faces_count * self.faces_count # number of all AT&T test images/faces\n test_correct = 0\n for face_id in range(1, self.faces_count + 1):\n for test_id in range(1, 11):\n if (test_id in self.training_ids[face_id-1]) == False: # we skip the image if it is part of the training set\n path_to_img = os.path.join(self.faces_dir,\n 's' + str(face_id), str(test_id) + '.pgm') # relative path\n\n result_id = self.classify(path_to_img)\n result = (int(result_id) == int(face_id))\n\n if result == True:\n test_correct += 1\n f.write('image: %s\\nresult: correct\\n\\n' % path_to_img)\n else:\n f.write('image: %s\\nresult: wrong, got %2d\\n\\n' %\n (path_to_img, result_id))\n\n self.accuracy = float(100. * test_correct / test_count)\n print ('---> Correct: ' + str(self.accuracy) + '%')\n f.write('Correct: %.2f\\n' % (self.accuracy))\n f.close() # closing the file\n\n \"\"\"\n Evaluate the model for the small celebrity data set.\n Returning the top 5 matches within the database.\n Images should have the same size (92,112) and are\n located in the test_dir folder.\n \"\"\"\n def evaluate_faces(self, test_dir='.'):\n print ('> Evaluating test faces')\n for img_name in os.listdir(test_dir): # go through all the celebrity images in the folder\n path_to_img = os.path.join(test_dir, img_name)\n\n img = cv2.imread(path_to_img, 0) # read as a grayscale image\n img_col = np.array(img, dtype='float64').flatten() # flatten the image\n img_col -= self.mean_img_col # subract the mean column\n img_col = np.reshape(img_col, (self.mn, 1)) # from row vector to col vector\n\n S = self.evectors.transpose() * img_col # projecting the normalized probe onto the\n # Eigenspace, to find out the weights\n\n diff = self.W - S # finding the min ||W_j - S||\n norms = np.linalg.norm(diff, axis=0)\n top5_ids = np.argpartition(norms, 5)[:5] # first five elements: indices of top 5 matches in AT&T set\n\n name_noext = os.path.splitext(img_name)[0] # the image file name without extension\n result_dir = os.path.join('results', name_noext) # path to the respective results folder\n os.makedirs(result_dir) # make a results folder for the respective celebrity\n result_file = os.path.join(result_dir, 'results.txt') # the file with the similarity value and id's\n\n f = open(result_file, 'w') # open the results file for writing\n\n topid_tuples = []\n\n for top_id in top5_ids:\n face_id = int(top_id / self.train_faces_count) + 1 # getting the face_id of one of the closest matches\n subface_id = self.training_ids[face_id-1][top_id % self.train_faces_count] # getting the exact subimage from the face\n\n path_to_img = os.path.join(self.faces_dir,\n 's' + str(face_id), str(subface_id) + '.pgm') # relative path to the top5 face\n\n shutil.copyfile(path_to_img, # copy the top face from source\n os.path.join(result_dir, str(top_id) + '.pgm')) # to destination\n \n topid_tuples.append(tuple((top_id, norms[top_id])))\n topid_tuples.sort(key=operator.itemgetter(1)) #sort by score\n\n best_face_id = 0\n best_subface_id = 0\n\n for i in range(0, 5):\n global_id = topid_tuples[i][0]\n score = topid_tuples[i][1]\n found_face_id = int(global_id / self.train_faces_count + 1)\n if (i==0):\n best_face_id = found_face_id\n best_subface_id = self.training_ids[found_face_id-1][global_id % self.train_faces_count]\n\n #Find name in database\n conn = sqlite3.connect('names.db')\n c = conn.cursor()\n c.execute('SELECT Name FROM Names WHERE Id='+str(found_face_id))\n user1 = c.fetchone()\n f.write('%3d. found face id: %3d, name: %s, pic id: %3d, score: %.6f\\n' % (i+1, found_face_id, user1[0], global_id, score)) # write the id and its score to the results file\n\n f.close() # close the results file\n \n #Show best match for last picture taken\n last_picture_id=1\n while os.path.isfile(os.path.join('test_faces', f'{last_picture_id}.jpg')) == True:\n last_picture_id += 1\n last_picture_id -= 1\n \n path_to_best = os.path.join(self.faces_dir, 's'+str(best_face_id), str(best_subface_id)+'.pgm')\n if (os.path.join('test_faces', f'{img_name}')) == (os.path.join('test_faces', f'{last_picture_id}.jpg')):\n best_match = cv2.imread(path_to_best)\n window_name = \"Best match for \" + str(img_name)\n cv2.namedWindow(window_name, cv2.WINDOW_NORMAL)\n cv2.imshow(window_name, best_match)\n cv2.resizeWindow(window_name, 184,224)\n cv2.waitKey(0) \n cv2.destroyAllWindows()\n \n print ('---> Evaluation done: check results directory')\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 2 or len(sys.argv) > 3:\n #print 'Usage: python2.7 eigenfaces.py ' \\\n #+ '<att faces dir> [<celebrity faces dir>]'\n sys.exit(1)\n\n if not os.path.exists('results'): # create a folder where to store the results\n os.makedirs('results')\n else:\n shutil.rmtree('results') # clear everything in the results folder\n os.makedirs('results')\n\n efaces = Eigenfaces(str(sys.argv[1])) # create the Eigenfaces object with the data dir\n efaces.evaluate() # evaluate our model\n\n # Saving the object containing the eigenvectors:\n with open('database.pkl', 'wb') as f:\n pickle.dump(efaces, f, pickle.HIGHEST_PROTOCOL)\n print('> Eigenvalues saved in database.pkl')\n\n #if len(sys.argv) == 3: # if we have third argument (celebrity folder)\n # efaces.evaluate_faces(str(sys.argv[2])) # find best matches for the celebrities\n\n" ]
[ [ "numpy.matrix", "numpy.linalg.norm", "numpy.empty", "numpy.reshape", "numpy.argmin", "numpy.array", "numpy.sum", "numpy.linalg.eig", "numpy.argpartition" ] ]
google-research/valan
[ "9fc6e38f411e6cb76408bf033cdc056ace980973" ]
[ "framework/log_ckpt_restoration.py" ]
[ "# coding=utf-8\n# Copyright 2019 Google LLC\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\"\"\"Extracts detailed checkpoint restoration information.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nfrom __future__ import print_function\n\nimport collections\nimport os\n\nfrom absl import logging\nimport tensorflow as tf\n\n\ndef log_status(ckpt_status, output_dir):\n \"\"\"Saves matched and unmatched object information to file for examination.\n\n Args:\n ckpt_status: a status object created by `assert_nontrivial_match()` or\n `assert_consumed()` methods of a checkpoint object, e.g.,\n ckpt = tf.Checkpoint(model=model)\n status = ckpt.restore(path_to_ckpt).assert_nontrivial_match()\n output_dir: str; the output dir to save detailed restoration log.\n \"\"\"\n try:\n \n ckpt = ckpt_status._checkpoint\n pretty_printer = _ObjectGraphProtoPrettyPrinter(\n ckpt.object_graph_proto)\n\n matched_objects = []\n unresolved_objects = []\n for node_id in range(len(ckpt.object_graph_proto.nodes)):\n text = '{}\\n'.format(pretty_printer.node_names[node_id])\n if node_id in ckpt.matched_proto_ids:\n matched_objects.append(text)\n else:\n unresolved_objects.append(text)\n\n unused_attributes = []\n for node_id, attribute_name in ckpt.unused_attributes.items():\n unused_attributes.append('Unused attribute in object {}: {}'.format(\n pretty_printer.node_names[node_id], attribute_name))\n except AttributeError:\n logging.error('Checkpoint status object must have attribute `_checkpoint`.')\n\n # Save information to file.\n if not tf.io.gfile.isdir(output_dir):\n logging.warning('Dir not found. Skip saving restoration information to: %s',\n output_dir)\n return\n\n output_file = os.path.join(output_dir, 'ckpt_restoration_log')\n with tf.io.gfile.GFile(output_file, 'w') as f:\n f.write('Restored checkpoint: {}\\n\\n'.format(ckpt.save_path_string))\n\n for fn in [f.write, logging.info]:\n fn('Unmatched objects: \\n -------------------------\\n')\n for text in unresolved_objects:\n fn(text)\n\n fn('\\n\\n\\n Unmatched attributes: \\n -------------------------\\n')\n for text in unused_attributes:\n fn(text)\n\n fn('\\n\\n\\n Matched objects: \\n -------------------------\\n')\n for text in matched_objects:\n fn(text)\n logging.info('Saved checkpoint restoration details to: %s', output_file)\n\n\nclass _ObjectGraphProtoPrettyPrinter(object):\n \"\"\"Lazily traverses an object graph proto to pretty print names.\n\n If no calls to `node_names` are made this object has no performance\n overhead. On the other hand, it will only traverse the object graph once, so\n repeated naming is cheap after the first.\n \"\"\"\n\n def __init__(self, object_graph_proto):\n self._object_graph_proto = object_graph_proto\n self._node_name_cache = None\n\n @property\n def node_names(self):\n \"\"\"Lazily creates a mapping from node id to (\"path\", \"to\", \"root\").\"\"\"\n if self._node_name_cache is not None:\n return self._node_name_cache\n path_to_root = {}\n path_to_root[0] = ('(root)',)\n to_visit = collections.deque([0])\n while to_visit:\n node_id = to_visit.popleft()\n obj = self._object_graph_proto.nodes[node_id]\n for child in obj.children:\n if child.node_id not in path_to_root:\n path_to_root[child.node_id] = (\n path_to_root[node_id] + (child.local_name,))\n to_visit.append(child.node_id)\n\n node_names = {}\n for node_id, path_to_root in path_to_root.items():\n node_names[node_id] = '.'.join(path_to_root)\n\n for node_id, node in enumerate(self._object_graph_proto.nodes):\n for slot_reference in node.slot_variables:\n node_names[slot_reference.slot_variable_node_id] = (\n '{}\\'s state \"{}\" for {}'.format(\n node_names[node_id], slot_reference.slot_name,\n node_names[slot_reference.original_variable_node_id]))\n self._node_name_cache = node_names\n return node_names\n" ]
[ [ "tensorflow.io.gfile.GFile", "tensorflow.io.gfile.isdir" ] ]
saullocastro/tudaesasII
[ "32c7e0fad9a58d783ce280270eb3556ad8946182" ]
[ "scripts_lectures/MDOF_systems/mdof10_plate_simply_supported_modes.py" ]
[ "import sys\nsys.path.append('../..')\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport numpy as np\nfrom scipy.linalg import eigh\nfrom composites.laminate import read_isotropic\n\nfrom tudaesasII.quad4r import Quad4R, update_K, update_M, DOF\n\n\nnx = 19\nny = 19\n\na = 1.\nb = 0.5\n\nE = 70.e9 # Pa\nnu = 0.33\n\nrho = 2.7e3 # kg/m3\nh = 0.001 # m\n\nxtmp = np.linspace(0, a, nx)\nytmp = np.linspace(0, b, ny)\nxmesh, ymesh = np.meshgrid(xtmp, ytmp)\nncoords = np.vstack((xmesh.T.flatten(), ymesh.T.flatten())).T\nx = ncoords[:, 0]\ny = ncoords[:, 1]\n\nnids = 1 + np.arange(ncoords.shape[0])\nnid_pos = dict(zip(nids, np.arange(len(nids))))\nnids_mesh = nids.reshape(nx, ny)\nn1s = nids_mesh[:-1, :-1].flatten()\nn2s = nids_mesh[1:, :-1].flatten()\nn3s = nids_mesh[1:, 1:].flatten()\nn4s = nids_mesh[:-1, 1:].flatten()\n\nplate = read_isotropic(thickness=h, E=E, nu=nu, calc_scf=True)\n\nK = np.zeros((DOF*nx*ny, DOF*nx*ny))\nM = np.zeros((DOF*nx*ny, DOF*nx*ny))\nquads = []\n\nfor n1, n2, n3, n4 in zip(n1s, n2s, n3s, n4s):\n pos1 = nid_pos[n1]\n pos2 = nid_pos[n2]\n pos3 = nid_pos[n3]\n pos4 = nid_pos[n4]\n r1 = ncoords[pos1]\n r2 = ncoords[pos2]\n r3 = ncoords[pos3]\n normal = np.cross(r2 - r1, r3 - r2)\n assert normal > 0 # guaranteeing that all elements have CCW positive normal\n quad = Quad4R()\n quad.rho = rho\n quad.n1 = n1\n quad.n2 = n2\n quad.n3 = n3\n quad.n4 = n4\n quad.scf13 = plate.scf_k13\n quad.scf23 = plate.scf_k23\n quad.h = h\n quad.ABDE = plate.ABDE\n update_K(quad, nid_pos, ncoords, K)\n update_M(quad, nid_pos, ncoords, M)\n quads.append(quad)\n\nprint('elements created')\n\n# applying boundary conditions\n# simply supported\nbk = np.zeros(K.shape[0], dtype=bool) #array to store known DOFs\ncheck = np.isclose(x, 0.) | np.isclose(x, a) | np.isclose(y, 0) | np.isclose(y, b)\nbk[2::DOF] = check\n\n#eliminating all u,v displacements\nbk[0::DOF] = True\nbk[1::DOF] = True\n\nbu = ~bk # same as np.logical_not, defining unknown DOFs\n\n# sub-matrices corresponding to unknown DOFs\nKuu = K[bu, :][:, bu]\nMuu = M[bu, :][:, bu]\n\np = 10\neigvals, U = eigh(a=Kuu, b=Muu, subset_by_index=(0, p-1))\nomegan = eigvals**0.5\n\nmodes = np.asarray([[0, 1, 2], [3, 4, 5]])\nfig, axes = plt.subplots(nrows=modes.shape[0], ncols=modes.shape[1],\n figsize=(15, 10))\nfor (i,j), mode in np.ndenumerate(modes):\n ax = axes[i, j]\n u = np.zeros(K.shape[0], dtype=float)\n u[bu] = U[:, mode]\n ax.contourf(xmesh, ymesh, u[2::DOF].reshape(xmesh.shape).T, cmap=cm.jet)\n ax.set_title('mode = %d\\n$\\omega=%1.2f rad/s$' % (mode+1, omegan[mode]))\nplt.show()\n\n" ]
[ [ "numpy.ndenumerate", "numpy.isclose", "numpy.asarray", "numpy.zeros", "scipy.linalg.eigh", "matplotlib.pyplot.subplots", "numpy.arange", "matplotlib.pyplot.show", "numpy.linspace", "numpy.meshgrid", "numpy.cross" ] ]
bio-ontology-research-group/ogcn
[ "2b9e3cbf14c826c02cd176b62842b4fc773fa723" ]
[ "RelAtt/rgcn_lp_attn.py" ]
[ "\"\"\"\r\nModeling Relational Data with Graph Convolutional Networks\r\nPaper: https://arxiv.org/abs/1703.06103\r\nCode: https://github.com/MichSchli/RelationPrediction\r\nDifference compared to MichSchli/RelationPrediction\r\n* Report raw metrics instead of filtered metrics.\r\n* By default, we use uniform edge sampling instead of neighbor-based edge\r\n sampling used in author's code. In practice, we find it achieves similar MRR. User could specify \"--edge-sampler=neighbor\" to switch\r\n to neighbor-based edge sampling.\r\n\"\"\"\r\n\r\nimport argparse\r\nimport numpy as np\r\nimport time\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport random\r\n# from dgl.data.knowledge_graph import load_data\r\nfrom dgl.contrib.data import load_data\r\n\r\nfrom relGraphConv import RelGraphConv\r\n\r\nimport logging\r\n\r\nlogging.basicConfig(level=logging.DEBUG)\r\n\r\nfrom baseRGCN import BaseRGCN\r\n\r\nimport utils\r\n\r\n\r\nclass EmbeddingLayer(nn.Module):\r\n def __init__(self, num_nodes, num_rels, h_dim):\r\n super(EmbeddingLayer, self).__init__()\r\n self.n_embedding = torch.nn.Embedding(num_nodes, h_dim)\r\n self.e_embedding = torch.nn.Embedding(num_rels, h_dim)\r\n self.num_nodes = num_nodes\r\n self.num_rels = num_rels\r\n self.h_dim = h_dim\r\n\r\n def forward(self, g, hn, r, he, norm):\r\n\r\n logging.debug(\"Embedding HN: \" + str(hn.shape) + \" \" + str(self.num_nodes) + \" \" + str(self.h_dim))\r\n logging.debug(\"Embedding HE: \" + str(he.shape) + \" \" + str(self.num_rels))\r\n logging.debug(\"Embedding HN: \" + str(self.n_embedding(hn.squeeze()).shape) + \" \" + str(self.num_nodes))\r\n logging.debug(\"Squeeze HE: \" + str(he.squeeze().shape))\r\n logging.debug(\"Embedding HE: \" + str(self.e_embedding(he.squeeze()).shape) + \" \" + str(self.num_rels))\r\n return self.n_embedding(hn.squeeze()), self.e_embedding(he.squeeze())\r\n\r\n\r\n# class EmbeddingLayer(nn.Module):\r\n# def __init__(self, num_nodes, num_rels, h_dim):\r\n# super(EmbeddingLayer, self).__init__()\r\n# self.n_embedding = torch.nn.Embedding(num_nodes, h_dim)\r\n# self.e_embedding = torch.nn.Embedding(num_rels, h_dim)\r\n\r\n# def forward(self, g, hn, r, he, norm):\r\n\r\n# logging.debug(\"Embedding HN: \" + str(hn.shape))\r\n# logging.debug(\"Embedding HE: \" + str(he.shape))\r\n# return self.n_embedding(hn.squeeze()), self.e_embedding(he.squeeze())\r\n\r\nclass RGCN(BaseRGCN):\r\n def build_input_layer(self):\r\n return EmbeddingLayer(self.num_nodes, self.num_rels,self.h_dim)\r\n\r\n def build_hidden_layer(self, idx):\r\n act = F.relu if idx < self.num_hidden_layers - 1 else None\r\n return RelGraphConv(self.h_dim, self.h_dim, self.num_rels, \"bdd\",\r\n self.num_bases, activation=act, self_loop=True,\r\n dropout=self.dropout, low_mem = True)\r\n\r\nclass LinkPredict(nn.Module):\r\n def __init__(self, in_dim, h_dim, num_rels,num_bases=-1,\r\n num_hidden_layers=1, dropout=0, attn_drop = 0, use_cuda=False, reg_param=0):\r\n super(LinkPredict, self).__init__()\r\n self.rgcn = RGCN(in_dim, h_dim, h_dim, num_rels * 2, num_bases,\r\n num_hidden_layers, dropout, use_cuda)\r\n self.reg_param = reg_param\r\n self.w_relation = nn.Parameter(torch.Tensor(num_rels, h_dim))\r\n nn.init.xavier_uniform_(self.w_relation,\r\n gain=nn.init.calculate_gain('relu'))\r\n\r\n def calc_score(self, embedding, triplets):\r\n # DistMult\r\n s = embedding[triplets[:,0]]\r\n r = self.w_relation[triplets[:,1]]\r\n o = embedding[triplets[:,2]]\r\n score = torch.sum(s * r * o, dim=1)\r\n return score\r\n\r\n def forward(self, g, h, r, he, norm):\r\n \r\n logging.debug(\"Link predict HN: \" + str(h.shape))\r\n logging.debug(\"Link predict HE: \" + str(he.shape))\r\n\r\n return self.rgcn.forward(g, h, r, he, norm)\r\n\r\n def regularization_loss(self, embedding):\r\n return torch.mean(embedding.pow(2)) + torch.mean(self.w_relation.pow(2))\r\n\r\n def get_loss(self, g, embed, triplets, labels):\r\n # triplets is a list of data samples (positive and negative)\r\n # each row in the triplets is a 3-tuple of (source, relation, destination)\r\n score = self.calc_score(embed, triplets)\r\n #logging.debug(\"score: \" + str(score))\r\n predict_loss = F.binary_cross_entropy_with_logits(score, labels)\r\n reg_loss = self.regularization_loss(embed)\r\n return predict_loss + self.reg_param * reg_loss\r\n\r\ndef node_norm_to_edge_norm(g, node_norm):\r\n g = g.local_var()\r\n # convert to edge norm\r\n g.ndata['norm'] = node_norm\r\n g.apply_edges(lambda edges : {'norm' : edges.dst['norm']})\r\n return g.edata['norm']\r\n\r\ndef main(args):\r\n # load graph data\r\n data = load_data(args.dataset)\r\n num_nodes = data.num_nodes\r\n train_data = data.train\r\n num_edges = len(train_data)\r\n valid_data = data.valid\r\n test_data = data.test\r\n num_rels = data.num_rels\r\n\r\n logging.debug(\"Num rels: \" + str(num_rels))\r\n\r\n # check cuda\r\n use_cuda = args.gpu >= 0 and torch.cuda.is_available()\r\n if use_cuda:\r\n torch.cuda.set_device(args.gpu)\r\n\r\n # create model\r\n model = LinkPredict(num_nodes,\r\n args.n_hidden,\r\n num_rels,\r\n num_bases=args.n_bases,\r\n num_hidden_layers=args.n_layers,\r\n dropout=args.dropout,\r\n attn_drop=args.attn_drop,\r\n use_cuda=use_cuda,\r\n reg_param=args.regularization)\r\n\r\n # validation and testing triplets\r\n valid_data = torch.LongTensor(valid_data)\r\n test_data = torch.LongTensor(test_data)\r\n\r\n # build test graph\r\n test_graph, test_rel, test_norm = utils.build_test_graph(\r\n num_nodes, num_rels, train_data)\r\n test_deg = test_graph.in_degrees(\r\n range(test_graph.number_of_nodes())).float().view(-1,1)\r\n test_node_id = torch.arange(0, num_nodes, dtype=torch.long).view(-1, 1)\r\n test_rel = torch.from_numpy(test_rel)\r\n test_edge_feat = torch.arange(0, num_rels*2, dtype=torch.long).view(-1, 1)\r\n \r\n test_norm = node_norm_to_edge_norm(test_graph, torch.from_numpy(test_norm).view(-1, 1))\r\n\r\n if use_cuda:\r\n model.cuda()\r\n\r\n # build adj list and calculate degrees for sampling\r\n adj_list, degrees = utils.get_adj_and_degrees(num_nodes, train_data)\r\n\r\n # optimizer\r\n optimizer = torch.optim.Adam(model.parameters(), lr=args.lr)\r\n\r\n model_state_file = 'model_statewn.pth'\r\n forward_time = []\r\n backward_time = []\r\n\r\n # training loop\r\n print(\"start training...\")\r\n\r\n epoch = 0\r\n best_mrr = 0\r\n while True:\r\n torch.set_grad_enabled(True)\r\n model.train()\r\n epoch += 1\r\n\r\n # perform edge neighborhood sampling to generate training graph and data\r\n g, node_id, edge_type, node_norm, data, labels = \\\r\n utils.generate_sampled_graph_and_labels(\r\n train_data, args.graph_batch_size, args.graph_split_size,\r\n num_rels, adj_list, degrees, args.negative_sample,\r\n args.edge_sampler)\r\n print(\"Done edge sampling\")\r\n\r\n logging.debug(\"Node id: \" + str(node_id.shape))\r\n logging.debug(\"Edge type: \" + str(edge_type.shape))\r\n\r\n # set node/edge feature\r\n node_id = torch.from_numpy(node_id).view(-1, 1).long()\r\n edge_feat = torch.arange(num_rels*2).view(-1, 1).long()\r\n edge_type = torch.from_numpy(edge_type)\r\n\r\n logging.debug(\"Node id: \" + str(node_id.shape))\r\n logging.debug(\"Edge type: \" + str(edge_type.shape))\r\n\r\n\r\n\r\n edge_norm = node_norm_to_edge_norm(g, torch.from_numpy(node_norm).view(-1, 1))\r\n logging.debug(\"Edge norm: \" + str(edge_norm.shape))\r\n\r\n\r\n data, labels = torch.from_numpy(data), torch.from_numpy(labels)\r\n deg = g.in_degrees(range(g.number_of_nodes())).float().view(-1, 1)\r\n if use_cuda:\r\n node_id, deg = node_id.cuda(), deg.cuda()\r\n edge_type, edge_norm, edge_feat = edge_type.cuda(), edge_norm.cuda(), edge_feat.cuda()\r\n data, labels = data.cuda(), labels.cuda()\r\n g = g.to(args.gpu)\r\n\r\n t0 = time.time()\r\n logging.debug(\"Node id: \" + str(type(node_id)) + \" \" + str(node_id.shape))\r\n logging.debug(\"Edge type: \" + str(type(edge_feat)) + \" \" + str(edge_feat.shape))\r\n\r\n embed, e_embed = model(g, node_id, edge_type, edge_feat, edge_norm)\r\n loss = model.get_loss(g, embed, data, labels)\r\n t1 = time.time()\r\n loss.backward()\r\n torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_norm) # clip gradients\r\n optimizer.step()\r\n t2 = time.time()\r\n\r\n forward_time.append(t1 - t0)\r\n backward_time.append(t2 - t1)\r\n print(\"Epoch {:04d} | Loss {:.4f} | Best MRR {:.4f} | Forward {:.4f}s | Backward {:.4f}s\".\r\n format(epoch, loss.item(), best_mrr, forward_time[-1], backward_time[-1]))\r\n\r\n optimizer.zero_grad()\r\n\r\n # validation\r\n if epoch % args.evaluate_every == 0:\r\n # perform validation on CPU because full graph is too large\r\n if use_cuda:\r\n model.cpu()\r\n torch.set_grad_enabled(False)\r\n model.eval()\r\n print(\"start eval\")\r\n embed, e_embed = model(test_graph, test_node_id, test_rel, test_edge_feat,test_norm)\r\n mrr = utils.calc_mrr(embed, model.w_relation, torch.LongTensor(train_data),\r\n valid_data, test_data, hits=[1, 3, 10], eval_bz=args.eval_batch_size,\r\n eval_p=args.eval_protocol)\r\n # save best model\r\n if best_mrr < mrr:\r\n best_mrr = mrr\r\n torch.save({'state_dict': model.state_dict(), 'epoch': epoch}, model_state_file)\r\n \r\n if epoch >= args.n_epochs:\r\n break\r\n \r\n if use_cuda:\r\n model.cuda()\r\n\r\n print(\"training done\")\r\n print(\"Mean forward time: {:4f}s\".format(np.mean(forward_time)))\r\n print(\"Mean Backward time: {:4f}s\".format(np.mean(backward_time)))\r\n\r\n print(\"\\nstart testing:\")\r\n # use best model checkpoint\r\n checkpoint = torch.load(model_state_file)\r\n if use_cuda:\r\n model.cpu() # test on CPU\r\n torch.set_grad_enabled(False)\r\n model.eval()\r\n model.load_state_dict(checkpoint['state_dict'])\r\n print(\"Using best epoch: {}\".format(checkpoint['epoch']))\r\n embed, e_embed = model(test_graph, test_node_id, test_rel, test_edge_feat,test_norm)\r\n utils.calc_mrr(embed, model.w_relation, torch.LongTensor(train_data), valid_data,\r\n test_data, hits=[1, 3, 10], eval_bz=args.eval_batch_size, eval_p=args.eval_protocol)\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser(description='RGCN')\r\n parser.add_argument(\"--dropout\", type=float, default=0.2,\r\n help=\"dropout probability\")\r\n parser.add_argument(\"--attn-drop\", type=float, default=0.2,\r\n help=\"attention dropout probability\")\r\n parser.add_argument(\"--n-hidden\", type=int, default=504,\r\n help=\"number of hidden units\")\r\n parser.add_argument(\"--gpu\", type=int, default=0,\r\n help=\"gpu\")\r\n parser.add_argument(\"--lr\", type=float, default=1e-3,\r\n help=\"learning rate\")\r\n parser.add_argument(\"--n-bases\", type=int, default=100,\r\n help=\"number of weight blocks for each relation\")\r\n parser.add_argument(\"--n-layers\", type=int, default=2,\r\n help=\"number of propagation rounds\")\r\n parser.add_argument(\"--n-epochs\", type=int, default=6000,\r\n help=\"number of minimum training epochs\")\r\n parser.add_argument(\"-d\", \"--dataset\", type=str, default='wn18', #FB15k-237\r\n help=\"dataset to use\")\r\n parser.add_argument(\"--eval-batch-size\", type=int, default=500,\r\n help=\"batch size when evaluating\")\r\n parser.add_argument(\"--eval-protocol\", type=str, default=\"filtered\",\r\n help=\"type of evaluation protocol: 'raw' or 'filtered' mrr\")\r\n parser.add_argument(\"--regularization\", type=float, default=0.01,\r\n help=\"regularization weight\")\r\n parser.add_argument(\"--grad-norm\", type=float, default=1.0,\r\n help=\"norm to clip gradient to\")\r\n parser.add_argument(\"--graph-batch-size\", type=int, default=30000,\r\n help=\"number of edges to sample in each iteration\")\r\n parser.add_argument(\"--graph-split-size\", type=float, default=0.5,\r\n help=\"portion of edges used as positive sample\")\r\n parser.add_argument(\"--negative-sample\", type=int, default=10,\r\n help=\"number of negative samples per positive sample\")\r\n parser.add_argument(\"--evaluate-every\", type=int, default=500,\r\n help=\"perform evaluation every n epochs\")\r\n parser.add_argument(\"--edge-sampler\", type=str, default=\"uniform\",\r\n help=\"type of edge sampler: 'uniform' or 'neighbor'\")\r\n\r\n args = parser.parse_args()\r\n print(args)\r\n main(args)" ]
[ [ "torch.nn.functional.binary_cross_entropy_with_logits", "torch.arange", "torch.set_grad_enabled", "numpy.mean", "torch.from_numpy", "torch.cuda.set_device", "torch.cuda.is_available", "torch.LongTensor", "torch.load", "torch.nn.init.calculate_gain", "torch.Tensor", "torch.nn.Embedding", "torch.sum" ] ]
honchardev/Fun
[ "ca7c0076e9bb3017c5d7e89aa7d5bd54a83c8ecc" ]
[ "AI/MullerBook/ch3/dbscan_overview.py" ]
[ "# DBSCAN - density-based spatial clustering of applications with noise.\n\n# DBSCAN works by identifying points that are in “crowded” regions of the feature\n# space, where many data points are close together.\n# These regions are referred to as dense regions in feature space.\n\n# The idea behind DBSCAN is that clusters form dense regions of data, separated by regions that are relatively empty.\n\n# Points that are within a dense region are called core samples (or core points).\n# If there are at least min_samples many data points within a distance of eps to a given\n# data point, that data point is classified as a core sample.\n\nimport matplotlib.pyplot as plt\n\nimport mglearn\n\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.datasets import make_blobs, make_moons\nfrom sklearn.preprocessing import StandardScaler\n\n\nX, y = make_blobs(n_samples=20, random_state=0)\n\ndbscan = DBSCAN()\nclusters = dbscan.fit_predict(X)\n\nprint(\"Cluster membershipd:\\n{0}\".format(clusters)) # [-1, -1, ..., -1, -1] - all points were assigned to noise\n\n# Increasing min_samples (going from top to bottom in the figure) means that fewer points will be core points, and \n# more points will be labeled as noise.\n\n# The parameter eps is somewhat more important, as it determines what it means for\n# points to be “close.” Setting eps to be very small will mean that no points are core\n# samples, and may lead to all points being labeled as noise. Setting eps to be very large\n# will result in all points forming a single cluster.\n\n# While DBSCAN doesn’t require setting the number of clusters explicitly, setting eps\n# implicitly controls how many clusters will be found.\n\nmglearn.plots.plot_dbscan()\nplt.show()\n\n\ndef dbscan_moon():\n X, y = make_moons(n_samples=200, noise=0.05, random_state=42)\n\n # rescale the data to zero mean and unit variance\n scaler = StandardScaler()\n scaler.fit(X)\n X_scaled = scaler.transform(X)\n\n # create & apply DBSCAN\n dbscan = DBSCAN()\n clusters = dbscan.fit_predict(X_scaled)\n\n # Plot cluster assignmets\n plt.scatter(X[:, 0], X[:, 1], c=clusters, cmap=mglearn.cm2, s=60)\n plt.xlabel('f0')\n plt.ylabel('f1')\n plt.show()\n\ndbscan_moon()\n" ]
[ [ "sklearn.datasets.make_blobs", "sklearn.preprocessing.StandardScaler", "matplotlib.pyplot.xlabel", "sklearn.cluster.DBSCAN", "matplotlib.pyplot.scatter", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.show", "sklearn.datasets.make_moons" ] ]
dtiarks/ThesisPlot
[ "b9eaa5f2b2c472667cb17b2ba5a0471c741f0abe" ]
[ "Chap3/Laser/zero_expansion.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 09 13:29:17 2017\n\n@author: daniel\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport os\nimport json\nimport io\n\nfreq = [49.8933, 57.7919, 55.29, 46.71, 58.315]\nTemp = [25.0, 30.0, 35.0, 40.0, 31.74]\nTs = np.arange(25.0, 40.0, 0.01)\n\n\n\n" ]
[ [ "numpy.arange" ] ]
LSijing/Bayesian-pde-inverse-problem
[ "4fa94f89e580364dc5c4babe5363589446b763d6" ]
[ "pdeinverse/utils.py" ]
[ "# -*- coding: utf-8 -*-\n\n\nimport numpy as np\n\n\ndef compute_PCA(X, mean=True, k=0, A=None, normalize=True):\n \"\"\"\n PCA w.r.t A-norm, where A is a positive definite matrix.\n X : column-wise data set with size n-by-m, i.e. m samples of n dimension\n k : number of modes required (not include mean)\n normalize : whether to normalize eigenvectors w.r.t A\n Output :\n phi : n-by-(k+1)\n w : eigenvalues\n \"\"\"\n\n n, m = X.shape\n phi = np.zeros((n, k + 1))\n if mean:\n phi[:, 0] = X.mean(1)\n X = X - np.tile(phi[:, 0].reshape((-1, 1)), (1, m))\n s3 = 'Nonzero mean'\n else:\n s3 = 'Zero mean'\n\n if A is None:\n w, v = np.linalg.eigh(X.transpose() @ X)\n s1 = 'without norm'\n else:\n w, v = np.linalg.eigh(X.transpose() @ A @ X)\n s1 = 'with norm-A'\n w = w[::-1]\n v = v[:, ::-1]\n w = np.sqrt(np.absolute(w))\n if normalize:\n phi[:, 1:] = (X @ v[:, 0:k]) / np.tile(w[0:k].reshape((1, -1)), (n, 1))\n s2 = 'normalized eigenvectors'\n else:\n phi[:, 1:] = X @ v[:, 0:k]\n s2 = 'unnormalized eigenvectors'\n # print('Done PCA : (X %d-by-%d)' % (n, m) + s2 + ' ' + s1 + '. ' + s3 + ' + %d dominant eigenvectors' % (k))\n return phi, w\n" ]
[ [ "numpy.zeros", "numpy.absolute" ] ]
JosephChataignon/pyclustering
[ "bf4f51a472622292627ec8c294eb205585e50f52" ]
[ "pyclustering/nnet/tests/unit/ut_dynamic_visualizer.py" ]
[ "\"\"\"!\n\n@brief Unit-tests for basic dynamic visualizer.\n\n@authors Andrei Novikov ([email protected])\n@date 2014-2020\n@copyright BSD-3-Clause\n\n\"\"\"\n\n\nimport unittest;\n\n# Generate images without having a window appear.\nimport matplotlib;\nmatplotlib.use('Agg');\n\n\nfrom pyclustering.nnet.dynamic_visualizer import dynamic_visualizer;\n\n\nclass DynamicVisualizerUnitTest(unittest.TestCase):\n def testVisualizeSignleDynamicNoCrash(self):\n t = [0, 1, 2, 3, 4, 5, 6, 7];\n y = [0, 0, 1, 2, 0, 1, 2, 0];\n\n visualizer = dynamic_visualizer(1);\n visualizer.append_dynamic(t, y);\n\n\n def testVisualizeMultipleDynamicNoCrash(self):\n t = [0, 1, 2, 3, 4, 5, 6, 7];\n y = [ [0, 0], [0, 0], [1, 0], [2, 1], [0, 2], [1, 0], [2, 1], [0, 2] ];\n\n visualizer = dynamic_visualizer(1);\n visualizer.append_dynamics(t, y);\n\n\n def testVisualizeSeparateSequenceNoCrash(self):\n t = [0, 1, 2, 3, 4, 5, 6, 7];\n y = [ [0, 0], [0, 0], [1, 0], [2, 1], [0, 2], [1, 0], [2, 1], [0, 2] ];\n\n visualizer = dynamic_visualizer(2);\n visualizer.append_dynamics(t, y, canvas=0, separate=True);\n\n\n def testVisualizeSeparateListNoCrash(self):\n t = [0, 1, 2, 3, 4, 5, 6, 7];\n y = [ [0, 0], [0, 0], [1, 0], [2, 1], [0, 2], [1, 0], [2, 1], [0, 2] ];\n\n visualizer = dynamic_visualizer(2);\n visualizer.append_dynamics(t, y, canvas=0, separate=[ [0], [1] ]);\n\n\n def testVisualizeSeveralDynamicsOneCanvasNoCrash(self):\n t1 = [0, 1, 2, 3, 4, 5, 6, 7];\n y1 = [0, 0, 1, 2, 0, 1, 2, 0];\n\n t2 = [0, 1, 2, 3, 4, 5, 6, 7];\n y2 = [ [0, 0], [0, 0], [1, 0], [2, 1], [0, 2], [1, 0], [2, 1], [0, 2] ];\n\n visualizer = dynamic_visualizer(1);\n visualizer.append_dynamic(t1, y1);\n visualizer.append_dynamics(t2, y2);\n\n\n def testVisualizeSeveralDynamicsSeveralCanvasesNoCrash(self):\n t1 = [0, 1, 2, 3, 4, 5, 6, 7];\n y1 = [0, 0, 1, 2, 0, 1, 2, 0];\n\n t2 = [0, 1, 2, 3, 4, 5, 6, 7];\n y2 = [ [0, 0], [0, 0], [1, 0], [2, 1], [0, 2], [1, 0], [2, 1], [0, 2] ];\n\n visualizer = dynamic_visualizer(3);\n visualizer.append_dynamic(t1, y1, canvas=0);\n visualizer.append_dynamics(t2, y2, canvas=1, separate=True);\n\n\n def testVisualizeDynamicWithColorNoCrash(self):\n t = [0, 1, 2, 3, 4, 5, 6, 7];\n y = [0, 0, 1, 2, 0, 1, 2, 0];\n\n visualizer = dynamic_visualizer(1);\n visualizer.append_dynamic(t, y, canvas=0, color='red');\n\n\n def testVisualizeUnusedCanvasesNoCrash(self):\n t = [0, 1, 2, 3, 4, 5, 6, 7];\n y = [0, 0, 1, 2, 0, 1, 2, 0];\n\n visualizer = dynamic_visualizer(3);\n visualizer.append_dynamic(t, y, canvas=0, color='red');" ]
[ [ "matplotlib.use" ] ]
kevinleewy/RL-GAN-Net
[ "709bd8e28872e86fc6b4674e2c578ee3f519268f" ]
[ "visualizer.py" ]
[ "import numpy as np\nimport os\nimport ntpath\nimport time\n#from misc import\nfrom PIL import Image\n#from misc import html\n\nclass Visualizer():\n def __init__(self, opt):\n # self.opt = opt\n self.display_id = opt.display_id\n self.use_html = 0\n self.win_size = opt.display_winsize\n self.name = opt.name\n if self.display_id > 0:\n import visdom\n self.vis = visdom.Visdom(port=opt.port_id)\n\n if self.use_html:\n self.web_dir = os.path.join(opt.checkpoints_dir, opt.name, 'web')\n self.img_dir = os.path.join(self.web_dir, 'images')\n print('create web directory %s...' % self.web_dir)\n util.mkdirs([self.web_dir, self.img_dir])\n\n def save_image(image_numpy, image_path):\n image_pil = Image.fromarray(image_numpy)\n image_pil.save(image_path)\n # |visuals|: dictionary of images to display or save\n def display_current_results(self, visuals, epoch, iter=0):\n if self.display_id > 0: # show images in the browser\n idx = 1\n for label, item in visuals.items():\n if 'pc' in label:\n self.vis.scatter(np.transpose(item),\n Y=None,\n opts=dict(title=label + str(iter), markersize=0.5),\n win=self.display_id + idx)\n elif 'img' in label:\n # the transpose: HxWxC -> CxHxW\n self.vis.image(np.transpose(item, (2,0,1)), opts=dict(title=label),\n win=self.display_id + idx)\n idx += 1\n\n if self.use_html: # save images to a html file\n for label, image_numpy in visuals.items():\n img_path = os.path.join(self.img_dir, 'epoch%.3d-%d_%s.png' % (epoch, iter, label))\n save_image(image_numpy, img_path)\n # update website\n webpage = html.HTML(self.web_dir, 'Experiment name = %s' % self.name, reflesh=1)\n for n in range(epoch, 0, -1):\n webpage.add_header('epoch [%d]' % n)\n ims = []\n txts = []\n links = []\n\n for label, image_numpy in visuals.items():\n img_path = 'epoch%.3d-%d_%s.png' % (n, iter, label)\n ims.append(img_path)\n txts.append(label)\n links.append(img_path)\n webpage.add_images(ims, txts, links, width=self.win_size)\n webpage.save()\n\n # errors: dictionary of error labels and values\n def plot_current_errors(self, epoch, counter_ratio, opt, errors):\n if not hasattr(self, 'plot_data'):\n self.plot_data = {'X':[],'Y':[], 'legend':list(errors.keys())}\n self.plot_data['X'].append(epoch + counter_ratio)\n self.plot_data['Y'].append([errors[k] for k in self.plot_data['legend']])\n self.vis.line(\n X=np.stack([np.array(self.plot_data['X'])]*len(self.plot_data['legend']),1),\n Y=np.array(self.plot_data['Y']),\n opts={\n 'title': self.name + ' loss over time',\n 'legend': self.plot_data['legend'],\n 'xlabel': 'epoch',\n 'ylabel': 'loss'},\n win=self.display_id)\n\n # errors: same format as |errors| of plotCurrentErrors\n def print_current_errors(self, epoch, i, errors, t):\n message = '(epoch: %d, iters: %d, time: %.3f) ' % (epoch, i, t)\n for k, v in errors.items():\n message += '%s: %.3f ' % (k, v)\n\n print(message)\n\n # save image to the disk\n def save_images(self, webpage, visuals, image_path):\n image_dir = webpage.get_image_dir()\n short_path = ntpath.basename(image_path[0])\n name = os.path.splitext(short_path)[0]\n\n webpage.add_header(name)\n ims = []\n txts = []\n links = []\n\n for label, image_numpy in visuals.items():\n image_name = '%s_%s.png' % (name, label)\n save_path = os.path.join(image_dir, image_name)\n save_image(image_numpy, save_path)\n\n ims.append(image_name)\n txts.append(label)\n links.append(image_name)\n webpage.add_images(ims, txts, links, width=self.win_size)\n" ]
[ [ "numpy.array", "numpy.transpose" ] ]
koryca/once-for-all
[ "0c476d9c74c89d8fcf3d5d43dda06c0c73faad51" ]
[ "ofa/imagenet_classification/run_manager/run_manager.py" ]
[ "# Once for All: Train One Network and Specialize it for Efficient Deployment\n# Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han\n# International Conference on Learning Representations (ICLR), 2020.\n\nimport math\nimport os\nimport random\nimport time\nimport json\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim\nfrom tqdm import tqdm\n\nfrom ofa.utils import get_net_info, cross_entropy_loss_with_soft_target, cross_entropy_with_label_smoothing\nfrom ofa.utils import AverageMeter, accuracy, write_log, mix_images, mix_labels, init_models\nfrom ofa.utils import MyRandomResizedCrop\n\n__all__ = ['RunManager']\n\nclass RunConfig:\n\n def __init__(self, n_epochs, init_lr, lr_schedule_type, lr_schedule_param,\n dataset, train_batch_size, test_batch_size, valid_size,\n opt_type, opt_param, weight_decay, label_smoothing, no_decay_keys,\n mixup_alpha,\n model_init, validation_frequency, print_frequency):\n self.n_epochs = n_epochs\n self.init_lr = init_lr\n self.lr_schedule_type = lr_schedule_type\n self.lr_schedule_param = lr_schedule_param\n\n self.dataset = dataset\n self.train_batch_size = train_batch_size\n self.test_batch_size = test_batch_size\n self.valid_size = valid_size\n\n self.opt_type = opt_type\n self.opt_param = opt_param\n self.weight_decay = weight_decay\n self.label_smoothing = label_smoothing\n self.no_decay_keys = no_decay_keys\n\n self.mixup_alpha = mixup_alpha\n\n self.model_init = model_init\n self.validation_frequency = validation_frequency\n self.print_frequency = print_frequency\n\n @property\n def config(self):\n config = {}\n for key in self.__dict__:\n if not key.startswith('_'):\n config[key] = self.__dict__[key]\n return config\n\n def copy(self):\n return RunConfig(**self.config)\n\n \"\"\" learning rate \"\"\"\n\n def calc_learning_rate(self, epoch, batch=0, nBatch=None):\n if self.lr_schedule_type == 'cosine':\n T_total = self.n_epochs * nBatch\n T_cur = epoch * nBatch + batch\n lr = 0.5 * self.init_lr * (1 + math.cos(math.pi * T_cur / T_total))\n elif self.lr_schedule_type is None:\n lr = self.init_lr\n else:\n raise ValueError('do not support: %s' % self.lr_schedule_type)\n return lr\n\n def adjust_learning_rate(self, optimizer, epoch, batch=0, nBatch=None):\n \"\"\" adjust learning of a given optimizer and return the new learning rate \"\"\"\n new_lr = self.calc_learning_rate(epoch, batch, nBatch)\n for param_group in optimizer.param_groups:\n param_group['lr'] = new_lr\n return new_lr\n\n def warmup_adjust_learning_rate(self, optimizer, T_total, nBatch, epoch, batch=0, warmup_lr=0):\n T_cur = epoch * nBatch + batch + 1\n new_lr = T_cur / T_total * (self.init_lr - warmup_lr) + warmup_lr\n for param_group in optimizer.param_groups:\n param_group['lr'] = new_lr\n return new_lr\n\n \"\"\" data provider \"\"\"\n\n @property\n def data_provider(self):\n raise NotImplementedError\n\n @property\n def train_loader(self):\n return self.data_provider.train\n\n @property\n def valid_loader(self):\n return self.data_provider.valid\n\n @property\n def test_loader(self):\n return self.data_provider.test\n\n def random_sub_train_loader(self, n_images, batch_size, num_worker=None, num_replicas=None, rank=None):\n return self.data_provider.build_sub_train_loader(n_images, batch_size, num_worker, num_replicas, rank)\n\n \"\"\" optimizer \"\"\"\n\n def build_optimizer(self, net_params):\n if self.no_decay_keys is not None:\n assert isinstance(net_params, list) and len(net_params) == 2\n net_params = [\n {'params': net_params[0], 'weight_decay': self.weight_decay},\n {'params': net_params[1], 'weight_decay': 0},\n ]\n else:\n net_params = [{'params': net_params, 'weight_decay': self.weight_decay}]\n\n if self.opt_type == 'sgd':\n opt_param = {} if self.opt_param is None else self.opt_param\n momentum, nesterov = opt_param.get('momentum', 0.9), opt_param.get('nesterov', True)\n optimizer = torch.optim.SGD(net_params, self.init_lr, momentum=momentum, nesterov=nesterov)\n elif self.opt_type == 'adam':\n optimizer = torch.optim.Adam(net_params, self.init_lr)\n else:\n raise NotImplementedError\n return optimizer\n\nclass RunManager:\n\n def __init__(self, path, net, run_config, init=True, measure_latency=None, no_gpu=False):\n self.path = path\n self.net = net\n self.run_config = run_config\n\n self.best_acc = 0\n self.start_epoch = 0\n\n os.makedirs(self.path, exist_ok=True)\n\n # move network to GPU if available\n if torch.cuda.is_available() and (not no_gpu):\n self.device = torch.device('cuda:0')\n self.net = self.net.to(self.device)\n cudnn.benchmark = True\n else:\n self.device = torch.device('cpu')\n # initialize model (default)\n if init:\n init_models(run_config.model_init)\n\n # net info\n net_info = get_net_info(self.net, self.run_config.data_provider.data_shape, measure_latency, True)\n with open('%s/net_info.txt' % self.path, 'w') as fout:\n fout.write(json.dumps(net_info, indent=4) + '\\n')\n # noinspection PyBroadException\n try:\n fout.write(self.network.module_str + '\\n')\n except Exception:\n pass\n fout.write('%s\\n' % self.run_config.data_provider.train.dataset.transform)\n fout.write('%s\\n' % self.run_config.data_provider.test.dataset.transform)\n fout.write('%s\\n' % self.network)\n\n # criterion\n if isinstance(self.run_config.mixup_alpha, float):\n self.train_criterion = cross_entropy_loss_with_soft_target\n elif self.run_config.label_smoothing > 0:\n self.train_criterion = \\\n lambda pred, target: cross_entropy_with_label_smoothing(pred, target, self.run_config.label_smoothing)\n else:\n self.train_criterion = nn.CrossEntropyLoss()\n self.test_criterion = nn.CrossEntropyLoss()\n\n # optimizer\n if self.run_config.no_decay_keys:\n keys = self.run_config.no_decay_keys.split('#')\n net_params = [\n self.network.get_parameters(keys, mode='exclude'), # parameters with weight decay\n self.network.get_parameters(keys, mode='include'), # parameters without weight decay\n ]\n else:\n # noinspection PyBroadException\n try:\n net_params = self.network.weight_parameters()\n except Exception:\n net_params = []\n for param in self.network.parameters():\n if param.requires_grad:\n net_params.append(param)\n self.optimizer = self.run_config.build_optimizer(net_params)\n\n self.net = torch.nn.DataParallel(self.net)\n\n \"\"\" save path and log path \"\"\"\n\n @property\n def save_path(self):\n if self.__dict__.get('_save_path', None) is None:\n save_path = os.path.join(self.path, 'checkpoint')\n os.makedirs(save_path, exist_ok=True)\n self.__dict__['_save_path'] = save_path\n return self.__dict__['_save_path']\n\n @property\n def logs_path(self):\n if self.__dict__.get('_logs_path', None) is None:\n logs_path = os.path.join(self.path, 'logs')\n os.makedirs(logs_path, exist_ok=True)\n self.__dict__['_logs_path'] = logs_path\n return self.__dict__['_logs_path']\n\n @property\n def network(self):\n return self.net.module if isinstance(self.net, nn.DataParallel) else self.net\n\n def write_log(self, log_str, prefix='valid', should_print=True, mode='a'):\n write_log(self.logs_path, log_str, prefix, should_print, mode)\n\n \"\"\" save and load models \"\"\"\n\n def save_model(self, checkpoint=None, is_best=False, model_name=None):\n if checkpoint is None:\n checkpoint = {'state_dict': self.network.state_dict()}\n\n if model_name is None:\n model_name = 'checkpoint.pth.tar'\n\n checkpoint['dataset'] = self.run_config.dataset # add `dataset` info to the checkpoint\n latest_fname = os.path.join(self.save_path, 'latest.txt')\n model_path = os.path.join(self.save_path, model_name)\n with open(latest_fname, 'w') as fout:\n fout.write(model_path + '\\n')\n torch.save(checkpoint, model_path)\n\n if is_best:\n best_path = os.path.join(self.save_path, 'model_best.pth.tar')\n torch.save({'state_dict': checkpoint['state_dict']}, best_path)\n\n def load_model(self, model_fname=None):\n latest_fname = os.path.join(self.save_path, 'latest.txt')\n if model_fname is None and os.path.exists(latest_fname):\n with open(latest_fname, 'r') as fin:\n model_fname = fin.readline()\n if model_fname[-1] == '\\n':\n model_fname = model_fname[:-1]\n # noinspection PyBroadException\n try:\n if model_fname is None or not os.path.exists(model_fname):\n model_fname = '%s/checkpoint.pth.tar' % self.save_path\n with open(latest_fname, 'w') as fout:\n fout.write(model_fname + '\\n')\n print(\"=> loading checkpoint '{}'\".format(model_fname))\n checkpoint = torch.load(model_fname, map_location='cpu')\n except Exception:\n print('fail to load checkpoint from %s' % self.save_path)\n return {}\n\n self.network.load_state_dict(checkpoint['state_dict'])\n if 'epoch' in checkpoint:\n self.start_epoch = checkpoint['epoch'] + 1\n if 'best_acc' in checkpoint:\n self.best_acc = checkpoint['best_acc']\n if 'optimizer' in checkpoint:\n self.optimizer.load_state_dict(checkpoint['optimizer'])\n\n print(\"=> loaded checkpoint '{}'\".format(model_fname))\n return checkpoint\n\n def save_config(self, extra_run_config=None, extra_net_config=None):\n \"\"\" dump run_config and net_config to the model_folder \"\"\"\n run_save_path = os.path.join(self.path, 'run.config')\n if not os.path.isfile(run_save_path):\n run_config = self.run_config.config\n if extra_run_config is not None:\n run_config.update(extra_run_config)\n json.dump(run_config, open(run_save_path, 'w'), indent=4)\n print('Run configs dump to %s' % run_save_path)\n\n try:\n net_save_path = os.path.join(self.path, 'net.config')\n net_config = self.network.config\n if extra_net_config is not None:\n net_config.update(extra_net_config)\n json.dump(net_config, open(net_save_path, 'w'), indent=4)\n print('Network configs dump to %s' % net_save_path)\n except Exception:\n print('%s do not support net config' % type(self.network))\n\n \"\"\" metric related \"\"\"\n\n def get_metric_dict(self):\n return {\n 'top1': AverageMeter(),\n 'top5': AverageMeter(),\n }\n\n def update_metric(self, metric_dict, output, labels):\n acc1, acc5 = accuracy(output, labels, topk=(1, 5))\n metric_dict['top1'].update(acc1[0].item(), output.size(0))\n metric_dict['top5'].update(acc5[0].item(), output.size(0))\n\n def get_metric_vals(self, metric_dict, return_dict=False):\n if return_dict:\n return {\n key: metric_dict[key].avg for key in metric_dict\n }\n else:\n return [metric_dict[key].avg for key in metric_dict]\n\n def get_metric_names(self):\n return 'top1', 'top5'\n\n \"\"\" train and test \"\"\"\n\n def validate(self, epoch=0, is_test=False, run_str='', net=None, data_loader=None, no_logs=False, train_mode=False):\n if net is None:\n net = self.net\n if not isinstance(net, nn.DataParallel):\n net = nn.DataParallel(net)\n\n if data_loader is None:\n data_loader = self.run_config.test_loader if is_test else self.run_config.valid_loader\n\n if train_mode:\n net.train()\n else:\n net.eval()\n\n losses = AverageMeter()\n metric_dict = self.get_metric_dict()\n\n with torch.no_grad():\n with tqdm(total=len(data_loader),\n desc='Validate Epoch #{} {}'.format(epoch + 1, run_str), disable=no_logs) as t:\n for i, (images, labels) in enumerate(data_loader):\n images, labels = images.to(self.device), labels.to(self.device)\n # compute output\n output = net(images)\n loss = self.test_criterion(output, labels)\n # measure accuracy and record loss\n self.update_metric(metric_dict, output, labels)\n\n losses.update(loss.item(), images.size(0))\n t.set_postfix({\n 'loss': losses.avg,\n **self.get_metric_vals(metric_dict, return_dict=True),\n 'img_size': images.size(2),\n })\n t.update(1)\n return losses.avg, self.get_metric_vals(metric_dict)\n\n def validate_all_resolution(self, epoch=0, is_test=False, net=None):\n if net is None:\n net = self.network\n if isinstance(self.run_config.data_provider.image_size, list):\n img_size_list, loss_list, top1_list, top5_list = [], [], [], []\n for img_size in self.run_config.data_provider.image_size:\n img_size_list.append(img_size)\n self.run_config.data_provider.assign_active_img_size(img_size)\n self.reset_running_statistics(net=net)\n loss, (top1, top5) = self.validate(epoch, is_test, net=net)\n loss_list.append(loss)\n top1_list.append(top1)\n top5_list.append(top5)\n return img_size_list, loss_list, top1_list, top5_list\n else:\n loss, (top1, top5) = self.validate(epoch, is_test, net=net)\n return [self.run_config.data_provider.active_img_size], [loss], [top1], [top5]\n\n def train_one_epoch(self, args, epoch, warmup_epochs=0, warmup_lr=0):\n # switch to train mode\n self.net.train()\n MyRandomResizedCrop.EPOCH = epoch # required by elastic resolution\n\n nBatch = len(self.run_config.train_loader)\n\n losses = AverageMeter()\n metric_dict = self.get_metric_dict()\n data_time = AverageMeter()\n\n with tqdm(total=nBatch,\n desc='{} Train Epoch #{}'.format(self.run_config.dataset, epoch + 1)) as t:\n end = time.time()\n for i, (images, labels) in enumerate(self.run_config.train_loader):\n MyRandomResizedCrop.BATCH = i\n data_time.update(time.time() - end)\n if epoch < warmup_epochs:\n new_lr = self.run_config.warmup_adjust_learning_rate(\n self.optimizer, warmup_epochs * nBatch, nBatch, epoch, i, warmup_lr,\n )\n else:\n new_lr = self.run_config.adjust_learning_rate(self.optimizer, epoch - warmup_epochs, i, nBatch)\n\n images, labels = images.to(self.device), labels.to(self.device)\n target = labels\n if isinstance(self.run_config.mixup_alpha, float):\n # transform data\n lam = random.betavariate(self.run_config.mixup_alpha, self.run_config.mixup_alpha)\n images = mix_images(images, lam)\n labels = mix_labels(\n labels, lam, self.run_config.data_provider.n_classes, self.run_config.label_smoothing\n )\n\n # soft target\n if args.teacher_model is not None:\n args.teacher_model.train()\n with torch.no_grad():\n soft_logits = args.teacher_model(images).detach()\n soft_label = F.softmax(soft_logits, dim=1)\n\n # compute output\n output = self.net(images)\n loss = self.train_criterion(output, labels)\n\n if args.teacher_model is None:\n loss_type = 'ce'\n else:\n if args.kd_type == 'ce':\n kd_loss = cross_entropy_loss_with_soft_target(output, soft_label)\n else:\n kd_loss = F.mse_loss(output, soft_logits)\n loss = args.kd_ratio * kd_loss + loss\n loss_type = '%.1fkd+ce' % args.kd_ratio\n\n # compute gradient and do SGD step\n self.net.zero_grad() # or self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n # measure accuracy and record loss\n losses.update(loss.item(), images.size(0))\n self.update_metric(metric_dict, output, target)\n\n t.set_postfix({\n 'loss': losses.avg,\n **self.get_metric_vals(metric_dict, return_dict=True),\n 'img_size': images.size(2),\n 'lr': new_lr,\n 'loss_type': loss_type,\n 'data_time': data_time.avg,\n })\n t.update(1)\n end = time.time()\n return losses.avg, self.get_metric_vals(metric_dict)\n\n def train(self, args, warmup_epoch=0, warmup_lr=0):\n for epoch in range(self.start_epoch, self.run_config.n_epochs + warmup_epoch):\n train_loss, (train_top1, train_top5) = self.train_one_epoch(args, epoch, warmup_epoch, warmup_lr)\n\n if (epoch + 1) % self.run_config.validation_frequency == 0:\n img_size, val_loss, val_acc, val_acc5 = self.validate_all_resolution(epoch=epoch, is_test=False)\n\n is_best = np.mean(val_acc) > self.best_acc\n self.best_acc = max(self.best_acc, np.mean(val_acc))\n val_log = 'Valid [{0}/{1}]\\tloss {2:.3f}\\t{5} {3:.3f} ({4:.3f})'. \\\n format(epoch + 1 - warmup_epoch, self.run_config.n_epochs,\n np.mean(val_loss), np.mean(val_acc), self.best_acc, self.get_metric_names()[0])\n val_log += '\\t{2} {0:.3f}\\tTrain {1} {top1:.3f}\\tloss {train_loss:.3f}\\t'. \\\n format(np.mean(val_acc5), *self.get_metric_names(), top1=train_top1, train_loss=train_loss)\n for i_s, v_a in zip(img_size, val_acc):\n val_log += '(%d, %.3f), ' % (i_s, v_a)\n self.write_log(val_log, prefix='valid', should_print=False)\n else:\n is_best = False\n\n self.save_model({\n 'epoch': epoch,\n 'best_acc': self.best_acc,\n 'optimizer': self.optimizer.state_dict(),\n 'state_dict': self.network.state_dict(),\n }, is_best=is_best)\n\n def reset_running_statistics(self, net=None, subset_size=2000, subset_batch_size=200, data_loader=None):\n from ofa.imagenet_classification.elastic_nn.utils import set_running_statistics\n if net is None:\n net = self.network\n if data_loader is None:\n data_loader = self.run_config.random_sub_train_loader(subset_size, subset_batch_size)\n set_running_statistics(net, data_loader)\n" ]
[ [ "numpy.mean", "torch.nn.functional.mse_loss", "torch.nn.functional.softmax", "torch.nn.CrossEntropyLoss", "torch.nn.DataParallel" ] ]
scolburn54/rcwa_tf
[ "50c7f6e477b2784c32586d6eddb13ef9e4adec02" ]
[ "src/solver.py" ]
[ "import tensorflow as tf\nimport numpy as np\nimport rcwa_utils\nimport tensor_utils\n\n\ndef initialize_params(wavelengths = [632.0],\n thetas = [0.0],\n phis = [0.0],\n pte = [1.0],\n ptm = [0.0],\n pixelsX = 1,\n pixelsY = 1,\n erd = 6.76,\n ers = 2.25,\n PQ = [11, 11],\n Lx = 0.7 * 632.0,\n Ly = 0.7 * 632.0,\n L = [632.0, 632.0],\n Nx = 512,\n eps_min = 1.0,\n eps_max = 12.11,\n blur_radius = 100.0):\n '''\n Initializes simulation parameters and hyperparameters.\n Args:\n wavelengths: A `list` of dtype `float` and length `batchSize` specifying\n the set of wavelengths over which to optimize.\n\n thetas: A `list` of dtype `float` and length `batchSize` specifying\n the set of polar angles over which to optimize.\n\n phis: A `list` of dtype `float` and length `batchSize` specifying the \n set of azimuthal angles over which to optimize.\n\n pte: A `list` of dtype `float` and length `batchSize` specifying the set\n of TE polarization component magnitudes over which to optimize. A \n magnitude of 0.0 means no TE component. Under normal incidence, the TE \n polarization is parallel to the y-axis.\n\n ptm: A `list` of dtype `float` and length `batchSize` specifying the set\n of TM polarization component magnitudes over which to optimize. A \n magnitude of 0.0 means no TM component. Under normal incidence, the TM \n polarization is parallel to the x-axis.\n\n pixelsX: An `int` specifying the x dimension of the metasurface in\n pixels that are of width `params['Lx']`.\n\n pixelsY: An `int` specifying the y dimension of the metasurface in\n pixels that are of width `params['Ly']`.\n\n erd: A `float` specifying the relative permittivity of the non-vacuum,\n constituent material of the device layer for shape optimizations.\n\n ers: A `float` specifying the relative permittivity of the substrate\n layer.\n\n PQ: A `list` of dtype `int` and length 2 specifying the number of \n Fourier harmonics in the x and y directions. The numbers should be odd\n values.\n\n Lx: A `float` specifying the unit cell pitch in the x direction in\n nanometers.\n\n Ly: A `float` specifying the unit cell pitch in the y direction in\n nanometers.\n\n L: A `list` of dtype `float` specifying the layer thicknesses in \n nanometers.\n\n Nx: An `int` specifying the number of sample points along the x \n direction in the unit cell.\n\n eps_min: A `float` specifying the minimum allowed permittivity for \n topology optimizations.\n\n eps_max: A `float` specifying the maximum allowed permittivity for \n topology optimizations.\n\n blur_radius: A `float` specifying the radius of the blur function with \n which a topology optimized permittivity density should be convolved.\n Returns:\n params: A `dict` containing simulation and optimization settings.\n '''\n\n # Define the `params` dictionary.\n params = dict({})\n\n # Units and tensor dimensions.\n params['nanometers'] = 1E-9\n params['degrees'] = np.pi / 180\n params['batchSize'] = len(wavelengths)\n params['pixelsX'] = pixelsX\n params['pixelsY'] = pixelsY\n params['Nlay'] = len(L)\n\n # Simulation tensor shapes.\n batchSize = params['batchSize']\n simulation_shape = (batchSize, pixelsX, pixelsY)\n\n # Batch parameters (wavelength, incidence angle, and polarization).\n lam0 = params['nanometers'] * tf.convert_to_tensor(wavelengths, dtype = tf.float32)\n lam0 = lam0[:, tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis]\n lam0 = tf.tile(lam0, multiples = (1, pixelsX, pixelsY, 1, 1, 1))\n params['lam0'] = lam0\n\n theta = params['degrees'] * tf.convert_to_tensor(thetas, dtype = tf.float32)\n theta = theta[:, tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis]\n theta = tf.tile(theta, multiples = (1, pixelsX, pixelsY, 1, 1, 1))\n params['theta'] = theta\n\n phi = params['degrees'] * tf.convert_to_tensor(phis, dtype = tf.float32)\n phi = phi[:, tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis]\n phi = tf.tile(phi, multiples = (1, pixelsX, pixelsY, 1, 1, 1))\n params['phi'] = phi\n\n pte = tf.convert_to_tensor(pte, dtype = tf.complex64)\n pte = pte[:, tf.newaxis, tf.newaxis, tf.newaxis]\n pte = tf.tile(pte, multiples = (1, pixelsX, pixelsY, 1))\n params['pte'] = pte\n\n ptm = tf.convert_to_tensor(ptm, dtype = tf.complex64)\n ptm = ptm[:, tf.newaxis, tf.newaxis, tf.newaxis]\n ptm = tf.tile(ptm, multiples = (1, pixelsX, pixelsY, 1))\n params['ptm'] = ptm\n\n # Device parameters.\n params['ur1'] = 1.0 # permeability in reflection region\n params['er1'] = 1.0 # permittivity in reflection region\n params['ur2'] = 1.0 # permeability in transmission region\n params['er2'] = 1.0 # permittivity in transmission region\n params['urd'] = 1.0 # permeability of device\n params['erd'] = erd # permittivity of device\n params['urs'] = 1.0 # permeability of substrate\n params['ers'] = ers # permittivity of substrate\n params['Lx'] = Lx * params['nanometers'] # period along x\n params['Ly'] = Ly * params['nanometers'] # period along y\n length_shape = (1, 1, 1, params['Nlay'], 1, 1)\n L = tf.convert_to_tensor(L, dtype = tf.complex64)\n L = L[tf.newaxis, tf.newaxis, tf.newaxis, :, tf.newaxis, tf.newaxis]\n params['L'] = L * params['nanometers'] #* tf.ones(shape = length_shape, dtype = tf.complex64)\n params['length_min'] = 0.1\n params['length_max'] = 2.0\n\n # RCWA parameters.\n params['PQ'] = PQ # number of spatial harmonics along x and y\n params['Nx'] = Nx # number of point along x in real-space grid\n if params['PQ'][1] == 1:\n params['Ny'] = 1\n else:\n params['Ny'] = int(np.round(params['Nx'] * params['Ly'] / params['Lx'])) # number of point along y in real-space grid\n\n # Coefficient for the argument of tf.math.sigmoid() when generating\n # permittivity distributions with geometric parameters.\n params['sigmoid_coeff'] = 1000.0\n\n # Polynomial order for rectangular resonators definition.\n params['rectangle_power'] = 200\n\n # Allowed permittivity range.\n params['eps_min'] = eps_min\n params['eps_max'] = eps_max\n\n # Upsampling for Fourier optics propagation.\n params['upsample'] = 1\n\n # Duty Cycle limits for gratings.\n params['duty_min'] = 0.1\n params['duty_max'] = 0.9\n\n # Permittivity density blur radius.\n params['blur_radius'] = blur_radius * params['nanometers']\n\n return params\n\n\ndef generate_coupled_cylindrical_resonators(r_x, r_y, params):\n '''\n Generates permittivity/permeability for a unit cell comprising 4 coupled\n elliptical resonators.\n Args:\n r_x: A `tf.Tensor` of shape `(1, pixelsX, pixelsY, 4)` specifying the \n x-axis diameters of the four cylinders.\n\n r_y: A `tf.Tensor` of shape `(1, pixelsX, pixelsY, 4)` specifying the \n y-axis diameters of the four cylinders.\n\n params: A `dict` containing simulation and optimization settings.\n Returns:\n ER_t: A `tf.Tensor` of shape `(batchSize, pixelsX, pixelsY, Nlayer, Nx, Ny)`\n specifying the relative permittivity distribution of the unit cell.\n\n UR_t: A `tf.Tensor` of shape `(batchSize, pixelsX, pixelsY, Nlayer, Nx, Ny)`\n specifying the relative permeability distribution of the unit cell.\n '''\n\n # Retrieve simulation size parameters.\n batchSize = params['batchSize']\n pixelsX = params['pixelsX']\n pixelsY = params['pixelsY']\n Nlay = params['Nlay']\n Nx = params['Nx']\n Ny = params['Ny']\n Lx = params['Lx']\n Ly = params['Ly']\n\n # Initialize relative permeability.\n materials_shape = (batchSize, pixelsX, pixelsY, Nlay, Nx, Ny)\n UR = params['urd'] * np.ones(materials_shape)\n\n # Define the cartesian cross section.\n dx = Lx / Nx # grid resolution along x\n dy = Ly / Ny # grid resolution along y\n xa = np.linspace(0, Nx - 1, Nx) * dx # x axis array\n xa = xa - np.mean(xa) # center x axis at zero\n ya = np.linspace(0, Ny - 1, Ny) * dy # y axis vector\n ya = ya - np.mean(ya) # center y axis at zero\n [y_mesh, x_mesh] = np.meshgrid(ya,xa)\n\n # Convert to tensors and expand and tile to match the simulation shape.\n y_mesh = tf.convert_to_tensor(y_mesh, dtype = tf.float32)\n y_mesh = y_mesh[tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, :, :]\n y_mesh = tf.tile(y_mesh, multiples = (batchSize, pixelsX, pixelsY, 1, 1, 1))\n x_mesh = tf.convert_to_tensor(x_mesh, dtype = tf.float32)\n x_mesh = x_mesh[tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, :, :]\n x_mesh = tf.tile(x_mesh, multiples = (batchSize, pixelsX, pixelsY, 1, 1, 1))\n\n # Nanopost centers.\n c1_x = -Lx / 4\n c1_y = -Ly / 4\n c2_x = -Lx / 4\n c2_y = Ly / 4\n c3_x = Lx / 4\n c3_y = -Ly / 4\n c4_x = Lx / 4\n c4_y = Ly / 4\n\n # Clip the optimization ranges.\n r_x = params['Lx'] * tf.clip_by_value(r_x, clip_value_min = 0.05, clip_value_max = 0.23)\n r_y = params['Ly'] * tf.clip_by_value(r_y, clip_value_min = 0.05, clip_value_max = 0.23)\n r_x = tf.tile(r_x, multiples = (batchSize, 1, 1, 1))\n r_y = tf.tile(r_y, multiples = (batchSize, 1, 1, 1))\n r_x = r_x[:, :, :, tf.newaxis, tf.newaxis, tf.newaxis, :]\n r_y = r_y[:, :, :, tf.newaxis, tf.newaxis, tf.newaxis, :]\n\n # Calculate the nanopost boundaries.\n c1 = 1 - ((x_mesh - c1_x) / r_x[:, :, :, :, :, :, 0]) ** 2 - ((y_mesh - c1_y) / r_y[:, :, :, :, :, :, 0]) ** 2\n c2 = 1 - ((x_mesh - c2_x) / r_x[:, :, :, :, :, :, 1]) ** 2 - ((y_mesh - c2_y) / r_y[:, :, :, :, :, :, 1]) ** 2\n c3 = 1 - ((x_mesh - c3_x) / r_x[:, :, :, :, :, :, 2]) ** 2 - ((y_mesh - c3_y) / r_y[:, :, :, :, :, :, 2]) ** 2\n c4 = 1 - ((x_mesh - c4_x) / r_x[:, :, :, :, :, :, 3]) ** 2 - ((y_mesh - c4_y) / r_y[:, :, :, :, :, :, 3]) ** 2\n\n # Build device layer.\n ER_c1 = tf.math.sigmoid(params['sigmoid_coeff'] * c1)\n ER_c2 = tf.math.sigmoid(params['sigmoid_coeff'] * c2)\n ER_c3 = tf.math.sigmoid(params['sigmoid_coeff'] * c3)\n ER_c4 = tf.math.sigmoid(params['sigmoid_coeff'] * c4)\n ER_t = 1 + (params['erd'] - 1) * (ER_c1 + ER_c2 + ER_c3 + ER_c4)\n\n # Build substrate and concatenate along the layers dimension.\n device_shape = (batchSize, pixelsX, pixelsY, 1, Nx, Ny)\n ER_substrate = params['ers'] * tf.ones(device_shape, dtype = tf.float32)\n ER_t = tf.concat(values = [ER_t, ER_substrate], axis = 3)\n\n # Cast to complex for subsequent calculations.\n ER_t = tf.cast(ER_t, dtype = tf.complex64)\n UR_t = tf.convert_to_tensor(UR, dtype = tf.float32)\n UR_t = tf.cast(UR_t, dtype = tf.complex64)\n\n return ER_t, UR_t\n\n\ndef generate_coupled_rectangular_resonators(r_x, r_y, params):\n '''\n Generates permittivity/permeability for a unit cell comprising 4 coupled\n rectangular cross section scatterers.\n Args:\n r_x: A `tf.Tensor` of shape `(1, pixelsX, pixelsY, 4)` specifying the \n x-axis widths of the four rectangles.\n\n r_y: A `tf.Tensor` of shape `(1, pixelsX, pixelsY, 4)` specifying the \n y-axis widths of the four rectangles.\n\n params: A `dict` containing simulation and optimization settings.\n Returns:\n ER_t: A `tf.Tensor` of shape `(batchSize, pixelsX, pixelsY, Nlayer, Nx, Ny)`\n specifying the relative permittivity distribution of the unit cell.\n\n UR_t: A `tf.Tensor` of shape `(batchSize, pixelsX, pixelsY, Nlayer, Nx, Ny)`\n specifying the relative permeability distribution of the unit cell.\n '''\n\n # Retrieve simulation size parameters.\n batchSize = params['batchSize']\n pixelsX = params['pixelsX']\n pixelsY = params['pixelsY']\n Nlay = params['Nlay']\n Nx = params['Nx']\n Ny = params['Ny']\n Lx = params['Lx']\n Ly = params['Ly']\n\n # Initialize relative permeability.\n materials_shape = (batchSize, pixelsX, pixelsY, Nlay, Nx, Ny)\n UR = params['urd'] * np.ones(materials_shape)\n\n # Define the cartesian cross section.\n dx = Lx / Nx # grid resolution along x\n dy = Ly / Ny # grid resolution along y\n xa = np.linspace(0, Nx - 1, Nx) * dx # x axis array\n xa = xa - np.mean(xa) # center x axis at zero\n ya = np.linspace(0, Ny - 1, Ny) * dy # y axis vector\n ya = ya - np.mean(ya) # center y axis at zero\n [y_mesh, x_mesh] = np.meshgrid(ya,xa)\n\n # Convert to tensors and expand and tile to match the simulation shape.\n y_mesh = tf.convert_to_tensor(y_mesh, dtype = tf.float32)\n y_mesh = y_mesh[tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, :, :]\n y_mesh = tf.tile(y_mesh, multiples = (batchSize, pixelsX, pixelsY, 1, 1, 1))\n x_mesh = tf.convert_to_tensor(x_mesh, dtype = tf.float32)\n x_mesh = x_mesh[tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, :, :]\n x_mesh = tf.tile(x_mesh, multiples = (batchSize, pixelsX, pixelsY, 1, 1, 1))\n\n # Nanopost centers.\n c1_x = -Lx / 4\n c1_y = -Ly / 4\n c2_x = -Lx / 4\n c2_y = Ly / 4\n c3_x = Lx / 4\n c3_y = -Ly / 4\n c4_x = Lx / 4\n c4_y = Ly / 4\n\n # Nanopost width ranges.\n r_x = params['Lx'] * tf.clip_by_value(r_x, clip_value_min = 0.05, clip_value_max = 0.23)\n r_y = params['Ly'] * tf.clip_by_value(r_y, clip_value_min = 0.05, clip_value_max = 0.23)\n r_x = tf.tile(r_x, multiples = (batchSize, 1, 1, 1))\n r_y = tf.tile(r_y, multiples = (batchSize, 1, 1, 1))\n r_x = r_x[:, :, :, tf.newaxis, tf.newaxis, tf.newaxis, :]\n r_y = r_y[:, :, :, tf.newaxis, tf.newaxis, tf.newaxis, :]\n\n # Calculate the nanopost boundaries.\n c1 = 1 - ((x_mesh - c1_x) / r_x[:, :, :, :, :, :, 0]) ** params['rectangle_power'] - ((y_mesh - c1_y) / r_y[:, :, :, :, :, :, 0]) ** params['rectangle_power']\n c2 = 1 - ((x_mesh - c2_x) / r_x[:, :, :, :, :, :, 1]) ** params['rectangle_power'] - ((y_mesh - c2_y) / r_y[:, :, :, :, :, :, 1]) ** params['rectangle_power']\n c3 = 1 - ((x_mesh - c3_x) / r_x[:, :, :, :, :, :, 2]) ** params['rectangle_power'] - ((y_mesh - c3_y) / r_y[:, :, :, :, :, :, 2]) ** params['rectangle_power']\n c4 = 1 - ((x_mesh - c4_x) / r_x[:, :, :, :, :, :, 3]) ** params['rectangle_power'] - ((y_mesh - c4_y) / r_y[:, :, :, :, :, :, 3]) ** params['rectangle_power']\n\n # Build device layer.\n ER_c1 = tf.math.sigmoid(params['sigmoid_coeff'] * c1)\n ER_c2 = tf.math.sigmoid(params['sigmoid_coeff'] * c2)\n ER_c3 = tf.math.sigmoid(params['sigmoid_coeff'] * c3)\n ER_c4 = tf.math.sigmoid(params['sigmoid_coeff'] * c4)\n ER_t = 1 + (params['erd'] - 1) * (ER_c1 + ER_c2 + ER_c3 + ER_c4)\n\n # Build substrate and concatenate along the layers dimension.\n device_shape = (batchSize, pixelsX, pixelsY, 1, Nx, Ny)\n ER_substrate = params['ers'] * tf.ones(device_shape, dtype = tf.float32)\n ER_t = tf.concat(values = [ER_t, ER_substrate], axis = 3)\n\n # Cast to complex for subsequent calculations.\n ER_t = tf.cast(ER_t, dtype = tf.complex64)\n UR_t = tf.convert_to_tensor(UR, dtype = tf.float32)\n UR_t = tf.cast(UR_t, dtype = tf.complex64)\n\n return ER_t, UR_t\n\n\ndef generate_rectangular_resonators(r_x, r_y, params):\n '''\n Generates permittivity/permeability for a unit cell comprising a single, \n centered rectangular cross section scatterer.\n\n Args:\n r_x: A `tf.Tensor` of shape `(1, pixelsX, pixelsY, 1)` specifying the \n x-axis widths of the rectangle.\n\n r_y: A `tf.Tensor` of shape `(1, pixelsX, pixelsY, 1)` specifying the \n y-axis widths of the rectangle.\n\n params: A `dict` containing simulation and optimization settings.\n Returns:\n ER_t: A `tf.Tensor` of shape `(batchSize, pixelsX, pixelsY, Nlayer, Nx, Ny)`\n specifying the relative permittivity distribution of the unit cell.\n\n UR_t: A `tf.Tensor` of shape `(batchSize, pixelsX, pixelsY, Nlayer, Nx, Ny)`\n specifying the relative permeability distribution of the unit cell.\n '''\n\n # Retrieve simulation size parameters.\n batchSize = params['batchSize']\n pixelsX = params['pixelsX']\n pixelsY = params['pixelsY']\n Nlay = params['Nlay']\n Nx = params['Nx']\n Ny = params['Ny']\n Lx = params['Lx']\n Ly = params['Ly']\n\n # Initialize relative permeability.\n materials_shape = (batchSize, pixelsX, pixelsY, Nlay, Nx, Ny)\n UR = params['urd'] * np.ones(materials_shape)\n\n # Define the cartesian cross section.\n dx = Lx / Nx # grid resolution along x\n dy = Ly / Ny # grid resolution along y\n xa = np.linspace(0, Nx - 1, Nx) * dx # x axis array\n xa = xa - np.mean(xa) # center x axis at zero\n ya = np.linspace(0, Ny - 1, Ny) * dy # y axis vector\n ya = ya - np.mean(ya) # center y axis at zero\n [y_mesh, x_mesh] = np.meshgrid(ya,xa)\n\n # Convert to tensors and expand and tile to match the simulation shape.\n y_mesh = tf.convert_to_tensor(y_mesh, dtype = tf.float32)\n y_mesh = y_mesh[tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, :, :]\n y_mesh = tf.tile(y_mesh, multiples = (batchSize, pixelsX, pixelsY, 1, 1, 1))\n x_mesh = tf.convert_to_tensor(x_mesh, dtype = tf.float32)\n x_mesh = x_mesh[tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, :, :]\n x_mesh = tf.tile(x_mesh, multiples = (batchSize, pixelsX, pixelsY, 1, 1, 1))\n\n # Limit the optimization ranges.\n r_x = params['Lx'] * tf.clip_by_value(r_x, clip_value_min = 0.05, clip_value_max = 0.46)\n r_y = params['Ly'] * tf.clip_by_value(r_y, clip_value_min = 0.05, clip_value_max = 0.46)\n r_x = tf.tile(r_x, multiples = (batchSize, 1, 1, 1))\n r_y = tf.tile(r_y, multiples = (batchSize, 1, 1, 1))\n r_x = r_x[:, :, :, tf.newaxis, tf.newaxis, tf.newaxis, :]\n r_y = r_y[:, :, :, tf.newaxis, tf.newaxis, tf.newaxis, :]\n\n r1 = 1 - tf.abs((x_mesh / 2 / r_x[:, :, :, :, :, :, 0]) - (y_mesh / 2 / r_y[:, :, :, :, :, :, 0])) - tf.abs((x_mesh / 2 / r_x[:, :, :, :, :, :, 0]) + (y_mesh / 2 / r_y[:, :, :, :, :, :, 0]))\n\n # Build device layer.\n ER_r1 = tf.math.sigmoid(params['sigmoid_coeff'] * r1)\n ER_t = 1 + (params['erd'] - 1) * ER_r1\n\n # Build substrate and concatenate along the layers dimension.\n device_shape = (batchSize, pixelsX, pixelsY, 1, Nx, Ny)\n ER_substrate = params['ers'] * tf.ones(device_shape, dtype = tf.float32)\n ER_t = tf.concat(values = [ER_t, ER_substrate], axis = 3)\n\n # Cast to complex for subsequent calculations.\n ER_t = tf.cast(ER_t, dtype = tf.complex64)\n UR_t = tf.convert_to_tensor(UR, dtype = tf.float32)\n UR_t = tf.cast(UR_t, dtype = tf.complex64)\n\n return ER_t, UR_t\n\n\ndef generate_elliptical_resonators(r_x, r_y, params):\n '''\n Generates permittivity/permeability for a unit cell comprising a single, \n centered elliptical cross section scatterer.\n\n Args:\n r_x: A `tf.Tensor` of shape `(1, pixelsX, pixelsY, 1)` specifying the \n x-axis diameter of the ellipse.\n\n r_y: A `tf.Tensor` of shape `(1, pixelsX, pixelsY, 1)` specifying the \n y-axis diameter of the ellipse.\n\n params: A `dict` containing simulation and optimization settings.\n Returns:\n ER_t: A `tf.Tensor` of shape `(batchSize, pixelsX, pixelsY, Nlayer, Nx, Ny)`\n specifying the relative permittivity distribution of the unit cell.\n\n UR_t: A `tf.Tensor` of shape `(batchSize, pixelsX, pixelsY, Nlayer, Nx, Ny)`\n specifying the relative permeability distribution of the unit cell.\n '''\n\n # Retrieve simulation size parameters.\n batchSize = params['batchSize']\n pixelsX = params['pixelsX']\n pixelsY = params['pixelsY']\n Nlay = params['Nlay']\n Nx = params['Nx']\n Ny = params['Ny']\n Lx = params['Lx']\n Ly = params['Ly']\n\n # Initialize relative permeability.\n materials_shape = (batchSize, pixelsX, pixelsY, Nlay, Nx, Ny)\n UR = params['urd'] * np.ones(materials_shape)\n\n # Define the cartesian cross section.\n dx = Lx / Nx # grid resolution along x\n dy = Ly / Ny # grid resolution along y\n xa = np.linspace(0, Nx - 1, Nx) * dx # x axis array\n xa = xa - np.mean(xa) # center x axis at zero\n ya = np.linspace(0, Ny - 1, Ny) * dy # y axis vector\n ya = ya - np.mean(ya) # center y axis at zero\n [y_mesh, x_mesh] = np.meshgrid(ya,xa)\n\n # Convert to tensors and expand and tile to match the simulation shape.\n y_mesh = tf.convert_to_tensor(y_mesh, dtype = tf.float32)\n y_mesh = y_mesh[tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, :, :]\n y_mesh = tf.tile(y_mesh, multiples = (batchSize, pixelsX, pixelsY, 1, 1, 1))\n x_mesh = tf.convert_to_tensor(x_mesh, dtype = tf.float32)\n x_mesh = x_mesh[tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, :, :]\n x_mesh = tf.tile(x_mesh, multiples = (batchSize, pixelsX, pixelsY, 1, 1, 1))\n\n # Limit the optimization ranges.\n r_x = params['Lx'] * tf.clip_by_value(r_x, clip_value_min = 0.05, clip_value_max = 0.46)\n r_y = params['Ly'] * tf.clip_by_value(r_y, clip_value_min = 0.05, clip_value_max = 0.46)\n r_x = tf.tile(r_x, multiples = (batchSize, 1, 1, 1))\n r_y = tf.tile(r_y, multiples = (batchSize, 1, 1, 1))\n r_x = r_x[:, :, :, tf.newaxis, tf.newaxis, tf.newaxis, :]\n r_y = r_y[:, :, :, tf.newaxis, tf.newaxis, tf.newaxis, :]\n\n # Calculate the ellipse boundary.\n c1 = 1 - (x_mesh / r_x[:, :, :, :, :, :, 0]) ** 2 - (y_mesh / r_y[:, :, :, :, :, :, 0]) ** 2\n \n # Build device layer.\n ER_c1 = tf.math.sigmoid(params['sigmoid_coeff'] * c1)\n ER_t = 1 + (params['erd'] - 1) * ER_c1\n\n # Build substrate and concatenate along the layers dimension.\n device_shape = (batchSize, pixelsX, pixelsY, 1, Nx, Ny)\n ER_substrate = params['ers'] * tf.ones(device_shape, dtype = tf.float32)\n ER_t = tf.concat(values = [ER_t, ER_substrate], axis = 3)\n\n # Cast to complex for subsequent calculations.\n ER_t = tf.cast(ER_t, dtype = tf.complex64)\n UR_t = tf.convert_to_tensor(UR, dtype = tf.float32)\n UR_t = tf.cast(UR_t, dtype = tf.complex64)\n\n return ER_t, UR_t\n\n\ndef generate_cylindrical_nanoposts(duty, params):\n '''\n Generates permittivity/permeability for a unit cell comprising a single, \n centered circular cross section scatterer.\n\n Args:\n duty: A `tf.Tensor` of shape `(1, pixelsX, pixelsY, 1)` specifying the \n duty cycle (diameter / period) of the cylindrical nanopost.\n\n params: A `dict` containing simulation and optimization settings.\n Returns:\n ER_t: A `tf.Tensor` of shape `(batchSize, pixelsX, pixelsY, Nlayer, Nx, Ny)`\n specifying the relative permittivity distribution of the unit cell.\n\n UR_t: A `tf.Tensor` of shape `(batchSize, pixelsX, pixelsY, Nlayer, Nx, Ny)`\n specifying the relative permeability distribution of the unit cell.\n '''\n\n # Retrieve simulation size parameters.\n batchSize = params['batchSize']\n pixelsX = params['pixelsX']\n pixelsY = params['pixelsY']\n Nlay = params['Nlay']\n Nx = params['Nx']\n Ny = params['Ny']\n\n # Initialize relative permeability.\n materials_shape = (batchSize, pixelsX, pixelsY, Nlay, Nx, Ny)\n UR = params['urd'] * np.ones(materials_shape)\n\n # Define the cartesian cross section.\n dx = params['Lx'] / Nx # grid resolution along x\n dy = params['Ly'] / Ny # grid resolution along y\n xa = np.linspace(0, Nx - 1, Nx) * dx # x axis array\n xa = xa - np.mean(xa) # center x axis at zero\n ya = np.linspace(0, Ny - 1, Ny) * dy # y axis vector\n ya = ya - np.mean(ya) # center y axis at zero\n [y_mesh, x_mesh] = np.meshgrid(ya,xa)\n\n # Convert to tensors and expand and tile to match the simulation shape.\n y_mesh = tf.convert_to_tensor(y_mesh, dtype = tf.float32)\n y_mesh = y_mesh[tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, :, :]\n y_mesh = tf.tile(y_mesh, multiples = (batchSize, pixelsX, pixelsY, 1, 1, 1))\n x_mesh = tf.convert_to_tensor(x_mesh, dtype = tf.float32)\n x_mesh = x_mesh[tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, :, :]\n x_mesh = tf.tile(x_mesh, multiples = (batchSize, pixelsX, pixelsY, 1, 1, 1))\n\n # Build device layer.\n a = tf.clip_by_value(duty, clip_value_min = params['duty_min'], clip_value_max = params['duty_max'])\n a = a[:, :, :, tf.newaxis, tf.newaxis, tf.newaxis]\n a = tf.tile(a, multiples = (1, 1, 1, 1, Nx, Ny))\n radius = 0.5 * params['Ly'] * a\n sigmoid_arg = (1 - (x_mesh / radius) ** 2 - (y_mesh / radius) ** 2)\n ER_t = tf.math.sigmoid(params['sigmoid_coeff'] * sigmoid_arg)\n ER_t = 1 + (params['erd'] - 1) * ER_t\n\n # Build substrate and concatenate along the layers dimension.\n device_shape = (batchSize, pixelsX, pixelsY, 1, Nx, Ny)\n ER_substrate = params['ers'] * tf.ones(device_shape, dtype = tf.float32)\n ER_t = tf.concat(values = [ER_t, ER_substrate], axis = 3)\n\n # Cast to complex for subsequent calculations.\n ER_t = tf.cast(ER_t, dtype = tf.complex64)\n UR_t = tf.convert_to_tensor(UR, dtype = tf.float32)\n UR_t = tf.cast(UR_t, dtype = tf.complex64)\n\n return ER_t, UR_t\n\n\ndef generate_stacked_cylindrical_nanoposts(duty, params):\n '''\n Generates permittivity/permeability for a unit cell comprising a stacked\n cylinders.\n\n Args:\n duty: A `tf.Tensor` of shape `(1, 1, 1, Nlay - 1, 1, 1)` specifying the \n thicknesses of the cylinders in each layer, excluding the substrate \n tihckness.\n\n params: A `dict` containing simulation and optimization settings.\n Returns:\n ER_t: A `tf.Tensor` of shape `(batchSize, pixelsX, pixelsY, Nlayer, Nx, Ny)`\n specifying the relative permittivity distribution of the unit cell.\n\n UR_t: A `tf.Tensor` of shape `(batchSize, pixelsX, pixelsY, Nlayer, Nx, Ny)`\n specifying the relative permeability distribution of the unit cell.\n '''\n\n # Retrieve simulation size parameters.\n batchSize = params['batchSize']\n pixelsX = params['pixelsX']\n pixelsY = params['pixelsY']\n Nlay = params['Nlay']\n Nx = params['Nx']\n Ny = params['Ny']\n\n # Initialize relative permeability.\n materials_shape = (batchSize, pixelsX, pixelsY, Nlay, Nx, Ny)\n UR = params['urd'] * np.ones(materials_shape)\n\n # Define the cartesian cross section.\n dx = params['Lx'] / Nx # grid resolution along x\n dy = params['Ly'] / Ny # grid resolution along y\n xa = np.linspace(0, Nx - 1, Nx) * dx # x axis array\n xa = xa - np.mean(xa) # center x axis at zero\n ya = np.linspace(0, Ny - 1, Ny) * dy # y axis vector\n ya = ya - np.mean(ya) # center y axis at zero\n [y_mesh, x_mesh] = np.meshgrid(ya,xa)\n\n # Convert to tensors and expand and tile to match the simulation shape.\n y_mesh = tf.convert_to_tensor(y_mesh, dtype = tf.float32)\n y_mesh = y_mesh[tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, :, :]\n y_mesh = tf.tile(y_mesh, multiples = (batchSize, pixelsX, pixelsY, Nlay - 1, 1, 1))\n x_mesh = tf.convert_to_tensor(x_mesh, dtype = tf.float32)\n x_mesh = x_mesh[tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, :, :]\n x_mesh = tf.tile(x_mesh, multiples = (batchSize, pixelsX, pixelsY, Nlay - 1, 1, 1))\n\n # Build device layer.\n a = tf.clip_by_value(duty, clip_value_min = params['duty_min'], clip_value_max = params['duty_max'])\n a = a[:, :, :, :, tf.newaxis, tf.newaxis]\n a = tf.tile(a, multiples = (1, 1, 1, 1, Nx, Ny))\n radius = 0.5 * params['Ly'] * a\n sigmoid_arg = (1 - (x_mesh / radius) ** 2 - (y_mesh / radius) ** 2)\n ER_t = tf.math.sigmoid(params['sigmoid_coeff'] * sigmoid_arg)\n ER_t = 1 + (params['erd'] - 1) * ER_t\n\n # Build substrate and concatenate along the layers dimension.\n device_shape = (batchSize, pixelsX, pixelsY, 1, Nx, Ny)\n ER_substrate = params['ers'] * tf.ones(device_shape, dtype = tf.float32)\n ER_t = tf.concat(values = [ER_t, ER_substrate], axis = 3)\n\n # Cast to complex for subsequent calculations.\n ER_t = tf.cast(ER_t, dtype = tf.complex64)\n UR_t = tf.convert_to_tensor(UR, dtype = tf.float32)\n UR_t = tf.cast(UR_t, dtype = tf.complex64)\n\n return ER_t, UR_t\n\n\ndef generate_rectangular_lines(duty, params):\n '''\n Generates permittivity/permeability for a unit cell comprising a single\n rectangle that spans the full y length and with width defined along the x\n direction.\n\n Args:\n duty: A `tf.Tensor` of shape `(1, pixelsX, pixelsY)` specifying the duty\n cycle (i.e., width / pitch) along the x direction for the rectangle.\n\n params: A `dict` containing simulation and optimization settings.\n Returns:\n ER_t: A `tf.Tensor` of shape `(batchSize, pixelsX, pixelsY, Nlayer, Nx, Ny)`\n specifying the relative permittivity distribution of the unit cell.\n\n UR_t: A `tf.Tensor` of shape `(batchSize, pixelsX, pixelsY, Nlayer, Nx, Ny)`\n specifying the relative permeability distribution of the unit cell.\n '''\n\n # Retrieve simulation size parameters.\n batchSize = params['batchSize']\n pixelsX = params['pixelsX']\n pixelsY = params['pixelsY']\n Nlay = params['Nlay']\n Nx = params['Nx']\n Ny = params['Ny']\n\n # Initialize relative permeability.\n materials_shape = (batchSize, pixelsX, pixelsY, Nlay, Nx, Ny)\n UR = params['urd'] * np.ones(materials_shape)\n\n # Define the cartesian cross section.\n dx = params['Lx'] / Nx # grid resolution along x\n dy = params['Ly'] / Ny # grid resolution along y\n xa = np.linspace(0, Nx - 1, Nx) * dx # x axis array\n xa = xa - np.mean(xa) # center x axis at zero\n ya = np.linspace(0, Ny - 1, Ny) * dy # y axis vector\n ya = ya - np.mean(ya) # center y axis at zero\n [y_mesh, x_mesh] = np.meshgrid(ya,xa)\n\n # Convert to tensors and expand and tile to match the simulation shape.\n y_mesh = tf.convert_to_tensor(y_mesh, dtype = tf.float32)\n y_mesh = y_mesh[tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, :, :]\n y_mesh = tf.tile(y_mesh, multiples = (batchSize, pixelsX, pixelsY, 1, 1, 1))\n x_mesh = tf.convert_to_tensor(x_mesh, dtype = tf.float32)\n x_mesh = x_mesh[tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, :, :]\n x_mesh = tf.tile(x_mesh, multiples = (batchSize, pixelsX, pixelsY, 1, 1, 1))\n\n # Build device layer.\n a = tf.clip_by_value(duty, clip_value_min = params['duty_min'], clip_value_max = params['duty_max'])\n a = a[:, :, :, tf.newaxis, tf.newaxis, tf.newaxis]\n a = tf.tile(a, multiples = (1, 1, 1, 1, Nx, Ny))\n radius = 0.5 * params['Ly'] * a\n sigmoid_arg = 1 - tf.math.abs(x_mesh / radius)\n ER_t = tf.math.sigmoid(params['sigmoid_coeff'] * sigmoid_arg)\n ER_t = 1 + (params['erd'] - 1) * ER_t\n\n # Build substrate and concatenate along the layers dimension.\n device_shape = (batchSize, pixelsX, pixelsY, 1, Nx, Ny)\n ER_substrate = params['ers'] * tf.ones(device_shape, dtype = tf.float32)\n ER_t = tf.concat(values = [ER_t, ER_substrate], axis = 3)\n\n # Cast to complex for subsequent calculations.\n ER_t = tf.cast(ER_t, dtype = tf.complex64)\n UR_t = tf.convert_to_tensor(UR, dtype = tf.float32)\n UR_t = tf.cast(UR_t, dtype = tf.complex64)\n\n return ER_t, UR_t\n\n\ndef generate_plasmonic_cylindrical_nanoposts(duty, params):\n '''\n Generates permittivity/permeability for a unit cell comprising a single, \n centered circular cross section plasmonic scatterer with a complex-valued\n permittivity.\n\n Args:\n duty: A `tf.Tensor` of shape `(1, pixelsX, pixelsY, 1)` specifying the \n duty cycle (diameter / period) of the cylindrical nanopost.\n\n params: A `dict` containing simulation and optimization settings.\n Returns:\n ER_t: A `tf.Tensor` of shape `(batchSize, pixelsX, pixelsY, Nlayer, Nx, Ny)`\n specifying the relative permittivity distribution of the unit cell.\n\n UR_t: A `tf.Tensor` of shape `(batchSize, pixelsX, pixelsY, Nlayer, Nx, Ny)`\n specifying the relative permeability distribution of the unit cell.\n '''\n\n # Retrieve simulation size parameters.\n batchSize = params['batchSize']\n pixelsX = params['pixelsX']\n pixelsY = params['pixelsY']\n Nlay = params['Nlay']\n Nx = params['Nx']\n Ny = params['Ny']\n\n # Initialize relative permeability.\n materials_shape = (batchSize, pixelsX, pixelsY, Nlay, Nx, Ny)\n UR = params['urd'] * np.ones(materials_shape)\n\n # Define the cartesian cross section.\n dx = params['Lx'] / Nx # grid resolution along x\n dy = params['Ly'] / Ny # grid resolution along y\n xa = np.linspace(0, Nx - 1, Nx) * dx # x axis array\n xa = xa - np.mean(xa) # center x axis at zero\n ya = np.linspace(0, Ny - 1, Ny) * dy # y axis vector\n ya = ya - np.mean(ya) # center y axis at zero\n [y_mesh, x_mesh] = np.meshgrid(ya,xa)\n\n # Convert to tensors and expand and tile to match the simulation shape.\n y_mesh = tf.convert_to_tensor(y_mesh, dtype = tf.float32)\n y_mesh = y_mesh[tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, :, :]\n y_mesh = tf.tile(y_mesh, multiples = (batchSize, pixelsX, pixelsY, 1, 1, 1))\n x_mesh = tf.convert_to_tensor(x_mesh, dtype = tf.float32)\n x_mesh = x_mesh[tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, :, :]\n x_mesh = tf.tile(x_mesh, multiples = (batchSize, pixelsX, pixelsY, 1, 1, 1))\n\n # Build device layer.\n a = tf.clip_by_value(duty, clip_value_min = params['duty_min'], clip_value_max = params['duty_max'])\n a = a[:, :, :, tf.newaxis, tf.newaxis, tf.newaxis]\n a = tf.tile(a, multiples = (1, 1, 1, 1, Nx, Ny))\n radius = 0.5 * params['Ly'] * a\n sigmoid_arg = (1 - (x_mesh / radius) ** 2 - (y_mesh / radius) ** 2)\n ER_t = tf.math.sigmoid(params['sigmoid_coeff'] * sigmoid_arg)\n ER_t = tf.cast(ER_t, dtype = tf.complex64)\n ER_t = 1 + (params['erd'] - 1) * ER_t\n\n # Build substrate and concatenate along the layers dimension.\n device_shape = (batchSize, pixelsX, pixelsY, 1, Nx, Ny)\n ER_substrate = params['ers'] * tf.ones(device_shape, dtype = tf.complex64)\n ER_t = tf.concat(values = [ER_t, ER_substrate], axis = 3)\n\n # Cast to complex for subsequent calculations.\n UR_t = tf.convert_to_tensor(UR, dtype = tf.float32)\n UR_t = tf.cast(UR_t, dtype = tf.complex64)\n\n return ER_t, UR_t\n\n\ndef generate_arbitrary_epsilon(eps_r, params):\n '''\n Generates permittivity/permeability for a unit cell comprising a continuously\n varying permittivity for each pixel in the Cartesian grid.\n\n Args:\n eps_r: A `tf.Tensor` of shape `(1, pixelsX, pixelsY, Nlayer - 1, Nx, Ny)`\n and type `tf.float32` specifying the permittivity at each point in the \n unit cell grid. The `Nlayer - 1` eps_r.shape[3] length corresponds to \n there being a fixed substrate that is unchanging between iterations.\n\n params: A `dict` containing simulation and optimization settings.\n Returns:\n ER_t: A `tf.Tensor` of shape `(batchSize, pixelsX, pixelsY, Nlayer, Nx, Ny)`\n specifying the relative permittivity distribution of the unit cell.\n\n UR_t: A `tf.Tensor` of shape `(batchSize, pixelsX, pixelsY, Nlayer, Nx, Ny)`\n specifying the relative permeability distribution of the unit cell.\n '''\n\n # Retrieve simulation size parameters.\n batchSize = params['batchSize']\n pixelsX = params['pixelsX']\n pixelsY = params['pixelsY']\n Nlay = params['Nlay']\n Nx = params['Nx']\n Ny = params['Ny']\n\n # Initialize relative permeability.\n materials_shape = (batchSize, pixelsX, pixelsY, Nlay, Nx, Ny)\n UR = params['urd'] * np.ones(materials_shape)\n\n # Set the permittivity.\n ER_t = tf.clip_by_value(eps_r, clip_value_min = params['eps_min'], clip_value_max = params['eps_max'])\n ER_t = tf.tile(ER_t, multiples = (batchSize, 1, 1, 1, 1, 1))\n\n # Build substrate and concatenate along the layers dimension.\n device_shape = (batchSize, pixelsX, pixelsY, 1, Nx, Ny)\n ER_substrate = params['ers'] * tf.ones(device_shape, dtype = tf.float32)\n ER_t = tf.concat(values = [ER_t, ER_substrate], axis = 3)\n\n # Cast to complex for subsequent calculations.\n ER_t = tf.cast(ER_t, dtype = tf.complex64)\n UR_t = tf.convert_to_tensor(UR, dtype = tf.float32)\n UR_t = tf.cast(UR_t, dtype = tf.complex64)\n\n return ER_t, UR_t\n\n\ndef make_propagator(params, f):\n '''\n Pre-computes the band-limited angular spectrum propagator for modelling\n free-space propagation for the distance and sampling as specified in `params`.\n\n Args:\n params: A `dict` containing simulation and optimization settings.\n\n f: A `float` specifying the focal length, or distance to propagate, in\n meters.\n Returns:\n propagator: a `tf.Tensor` of shape `(batchSize, params['upsample'] * pixelsX,\n params['upsample'] * pixelsY)` and dtype `tf.complex64` defining the \n reciprocal space, band-limited angular spectrum propagator.\n '''\n\n # Simulation tensor shape.\n batchSize = params['batchSize']\n pixelsX = params['pixelsX']\n pixelsY = params['pixelsY']\n upsample = params['upsample']\n\n # Propagator definition.\n k = 2 * np.pi / params['lam0'][:, 0, 0, 0, 0, 0]\n k = k[:, np.newaxis, np.newaxis]\n samp = params['upsample'] * pixelsX\n k = tf.tile(k, multiples = (1, 2 * samp - 1, 2 * samp - 1))\n k = tf.cast(k, dtype = tf.complex64) \n k_xlist_pos = 2 * np.pi * np.linspace(0, 1 / (2 * params['Lx'] / params['upsample']), samp) \n front = k_xlist_pos[-(samp - 1):]\n front = -front[::-1]\n k_xlist = np.hstack((front, k_xlist_pos))\n k_x = np.kron(k_xlist, np.ones((2 * samp - 1, 1)))\n k_x = k_x[np.newaxis, :, :]\n k_y = np.transpose(k_x, axes = [0, 2, 1])\n k_x = tf.convert_to_tensor(k_x, dtype = tf.complex64)\n k_x = tf.tile(k_x, multiples = (batchSize, 1, 1))\n k_y = tf.convert_to_tensor(k_y, dtype = tf.complex64)\n k_y = tf.tile(k_y, multiples = (batchSize, 1, 1))\n k_z_arg = tf.square(k) - (tf.square(k_x) + tf.square(k_y))\n k_z = tf.sqrt(k_z_arg)\n propagator_arg = 1j * k_z * f\n propagator = tf.exp(propagator_arg)\n\n # Limit transfer function bandwidth to prevent aliasing.\n kx_limit = 2 * np.pi * (((1 / (pixelsX * params['Lx'])) * f) ** 2 + 1) ** (-0.5) / params['lam0'][:, 0, 0, 0, 0, 0]\n kx_limit = tf.cast(kx_limit, dtype = tf.complex64)\n ky_limit = kx_limit\n kx_limit = kx_limit[:, tf.newaxis, tf.newaxis]\n ky_limit = ky_limit[:, tf.newaxis, tf.newaxis]\n\n # Apply the antialiasing filter.\n ellipse_kx = (tf.square(k_x / kx_limit) + tf.square(k_y / k)).numpy() <= 1\n ellipse_ky = (tf.square(k_x / k) + tf.square(k_y / ky_limit)).numpy() <= 1\n propagator = propagator * ellipse_kx * ellipse_ky\n\n return propagator\n\n\ndef propagate(field, propagator, upsample):\n '''\n Propagates a batch of input fields to a parallel output plane using the \n band-limited angular spectrum method.\n\n Args:\n field: A `tf.Tensor` of shape `(batchSize, params['upsample'] * pixelsX,\n params['upsample'] * pixelsY)` and dtype `tf.complex64` specifying the \n input electric fields to be diffracted to the output plane.\n\n propagator: a `tf.Tensor` of shape `(batchSize, params['upsample'] * pixelsX,\n params['upsample'] * pixelsY)` and dtype `tf.complex64` defining the \n reciprocal space, band-limited angular spectrum propagator.\n\n upsample: An odd-valued `int` specifying the factor by which the\n transverse field data stored in `field` should be upsampled.\n Returns:\n out: A `tf.Tensor` of shape `(batchSize, params['upsample'] * pixelsX,\n params['upsample'] * pixelsY)` and dtype `tf.complex64` specifying the \n the electric fields at the output plane.\n '''\n\n # Zero pad `field` to be a stack of 2n-1 x 2n-1 matrices\n # Put batch parameter last for padding then transpose back.\n _, _, m = field.shape\n n = upsample * m\n field = tf.transpose(field, perm = [1, 2, 0])\n field_real = tf.math.real(field)\n field_imag = tf.math.imag(field)\n field_real = tf.image.resize(field_real, [n, n], method = 'nearest')\n field_imag = tf.image.resize(field_imag, [n, n], method = 'nearest')\n field = tf.cast(field_real, dtype = tf.complex64) + 1j * tf.cast(field_imag, dtype = tf.complex64)\n field = tf.image.resize_with_crop_or_pad(field, 2 * n - 1, 2 * n - 1)\n field = tf.transpose(field, perm = [2, 0, 1])\n\n # Apply the propagator in Fourier space.\n field_freq = tf.signal.fftshift(tf.signal.fft2d(field), axes = (1, 2))\n field_filtered = tf.signal.ifftshift(field_freq * propagator, axes = (1, 2))\n out = tf.signal.ifft2d(field_filtered)\n\n # Crop back down to n x n matrices.\n out = tf.transpose(out, perm = [1, 2, 0])\n out = tf.image.resize_with_crop_or_pad(out, n, n)\n out = tf.transpose(out, perm = [2, 0, 1])\n\n return out\n\n\ndef define_input_fields(params):\n '''\n Given the batch of input conditions with different wavelengths and incidence\n angles, this gives the input source fields incident on the metasurface.\n\n Args:\n params: A `dict` containing simulation and optimization settings.\n Returns:\n A `tf.Tensor` of shape `(batchSize, pixelsX, pixelsY)` and dtype \n `tf.complex64` specifying the source fields injected onto a metasurface\n at the input.\n '''\n\n # Define the cartesian cross section.\n pixelsX = params['pixelsX']\n pixelsY = params['pixelsY']\n dx = params['Lx'] # grid resolution along x\n dy = params['Ly'] # grid resolution along y\n xa = np.linspace(0, pixelsX - 1, pixelsX) * dx # x axis array\n xa = xa - np.mean(xa) # center x axis at zero\n ya = np.linspace(0, pixelsY - 1, pixelsY) * dy # y axis vector\n ya = ya - np.mean(ya) # center y axis at zero\n [y_mesh, x_mesh] = np.meshgrid(ya, xa)\n x_mesh = x_mesh[np.newaxis, :, :]\n y_mesh = y_mesh[np.newaxis, :, :]\n\n # Extract the batch of wavelengths and input thetas.\n lam_phase_test = params['lam0'][:, 0, 0, 0, 0, 0]\n lam_phase_test = lam_phase_test[:, tf.newaxis, tf.newaxis]\n theta_phase_test = params['theta'][:, 0, 0, 0, 0, 0]\n theta_phase_test = theta_phase_test[:, tf.newaxis, tf.newaxis]\n\n # Apply a linear phase ramp based on the wavelength and thetas.\n phase_def = 2 * np.pi * np.sin(theta_phase_test) * x_mesh / lam_phase_test\n phase_def = tf.cast(phase_def, dtype = tf.complex64)\n\n return tf.exp(1j * phase_def)\n\n\ndef simulate(ER_t, UR_t, params = initialize_params()):\n '''\n Calculates the transmission/reflection coefficients for a unit cell with a\n given permittivity/permeability distribution and the batch of input conditions \n (e.g., wavelengths, wavevectors, polarizations) for a fixed real space grid\n and number of Fourier harmonics.\n\n Args:\n ER_t: A `tf.Tensor` of shape `(batchSize, pixelsX, pixelsY, Nlayer, Nx, Ny)`\n and dtype `tf.complex64` specifying the relative permittivity distribution\n of the unit cell.\n\n UR_t: A `tf.Tensor` of shape `(batchSize, pixelsX, pixelsY, Nlayer, Nx, Ny)`\n and dtype `tf.complex64` specifying the relative permeability distribution\n of the unit cell.\n\n params: A `dict` containing simulation and optimization settings.\n Returns:\n outputs: A `dict` containing the keys {'rx', 'ry', 'rz', 'R', 'ref', \n 'tx', 'ty', 'tz', 'T', 'TRN'} corresponding to the computed reflection/tranmission\n coefficients and powers.\n '''\n\n # Extract commonly used parameters from the `params` dictionary.\n batchSize = params['batchSize']\n pixelsX = params['pixelsX']\n pixelsY = params['pixelsY']\n Nlay = params['Nlay']\n PQ = params['PQ']\n\n ### Step 3: Build convolution matrices for the permittivity and permeability ###\n ERC = rcwa_utils.convmat(ER_t, PQ[0], PQ[1])\n URC = rcwa_utils.convmat(UR_t, PQ[0], PQ[1])\n\n ### Step 4: Wave vector expansion ###\n I = np.eye(np.prod(PQ), dtype = complex)\n I = tf.convert_to_tensor(I, dtype = tf.complex64)\n I = I[tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, :, :]\n I = tf.tile(I, multiples = (batchSize, pixelsX, pixelsY, Nlay, 1, 1))\n Z = np.zeros((np.prod(PQ), np.prod(PQ)), dtype = complex)\n Z = tf.convert_to_tensor(Z, dtype = tf.complex64)\n Z = Z[tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, :, :]\n Z = tf.tile(Z, multiples = (batchSize, pixelsX, pixelsY, Nlay, 1, 1))\n n1 = np.sqrt(params['er1'])\n n2 = np.sqrt(params['er2'])\n\n k0 = tf.cast(2 * np.pi / params['lam0'], dtype = tf.complex64)\n kinc_x0 = tf.cast(n1 * tf.sin(params['theta']) * tf.cos(params['phi']), dtype = tf.complex64)\n kinc_y0 = tf.cast(n1 * tf.sin(params['theta']) * tf.sin(params['phi']), dtype = tf.complex64)\n kinc_z0 = tf.cast(n1 * tf.cos(params['theta']), dtype = tf.complex64)\n kinc_z0 = kinc_z0[:, :, :, 0, :, :]\n\n # Unit vectors\n T1 = np.transpose([2 * np.pi / params['Lx'], 0])\n T2 = np.transpose([0, 2 * np.pi / params['Ly']])\n p_max = np.floor(PQ[0] / 2.0)\n q_max = np.floor(PQ[1] / 2.0)\n p = tf.constant(np.linspace(-p_max, p_max, PQ[0]), dtype = tf.complex64) # indices along T1\n p = p[tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, :, tf.newaxis]\n p = tf.tile(p, multiples = (1, pixelsX, pixelsY, Nlay, 1, 1))\n q = tf.constant(np.linspace(-q_max, q_max, PQ[1]), dtype = tf.complex64) # indices along T2\n q = q[tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, :]\n q = tf.tile(q, multiples = (1, pixelsX, pixelsY, Nlay, 1, 1))\n\n # Build Kx and Ky matrices\n kx_zeros = tf.zeros(PQ[1], dtype = tf.complex64)\n kx_zeros = kx_zeros[tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, :]\n ky_zeros = tf.zeros(PQ[0], dtype = tf.complex64)\n ky_zeros = ky_zeros[tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis, :, tf.newaxis]\n kx = kinc_x0 - 2 * np.pi * p / (k0 * params['Lx']) - kx_zeros\n ky = kinc_y0 - 2 * np.pi * q / (k0 * params['Ly']) - ky_zeros\n\n kx_T = tf.transpose(kx, perm = [0, 1, 2, 3, 5, 4])\n KX = tf.reshape(kx_T, shape = (batchSize, pixelsX, pixelsY, Nlay, np.prod(PQ)))\n KX = tf.linalg.diag(KX)\n\n ky_T = tf.transpose(ky, perm = [0, 1, 2, 3, 5, 4])\n KY = tf.reshape(ky_T, shape = (batchSize, pixelsX, pixelsY, Nlay, np.prod(PQ)))\n KY = tf.linalg.diag(KY)\n\n KZref = tf.linalg.matmul(tf.math.conj(params['ur1'] * I), tf.math.conj(params['er1'] * I))\n KZref = KZref - tf.linalg.matmul(KX, KX) - tf.linalg.matmul(KY, KY)\n KZref = tf.math.sqrt(KZref)\n KZref = -tf.math.conj(KZref)\n\n KZtrn = tf.linalg.matmul(tf.math.conj(params['ur2'] * I), tf.math.conj(params['er2'] * I))\n KZtrn = KZtrn - tf.linalg.matmul(KX, KX) - tf.linalg.matmul(KY, KY)\n KZtrn = tf.math.sqrt(KZtrn)\n KZtrn = tf.math.conj(KZtrn)\n\n ### Step 5: Free Space ###\n KZ = I - tf.linalg.matmul(KX, KX) - tf.linalg.matmul(KY, KY)\n KZ = tf.math.sqrt(KZ)\n KZ = tf.math.conj(KZ)\n\n Q_free_00 = tf.linalg.matmul(KX, KY)\n Q_free_01 = I - tf.linalg.matmul(KX, KX)\n Q_free_10 = tf.linalg.matmul(KY, KY) - I\n Q_free_11 = -tf.linalg.matmul(KY, KX)\n Q_free_row0 = tf.concat([Q_free_00, Q_free_01], axis = 5)\n Q_free_row1 = tf.concat([Q_free_10, Q_free_11], axis = 5)\n Q_free = tf.concat([Q_free_row0, Q_free_row1], axis = 4)\n\n W0_row0 = tf.concat([I, Z], axis = 5)\n W0_row1 = tf.concat([Z, I], axis = 5)\n W0 = tf.concat([W0_row0, W0_row1], axis = 4)\n\n LAM_free_row0 = tf.concat([1j * KZ, Z], axis = 5)\n LAM_free_row1 = tf.concat([Z, 1j * KZ], axis = 5)\n LAM_free = tf.concat([LAM_free_row0, LAM_free_row1], axis = 4)\n\n V0 = tf.linalg.matmul(Q_free, tf.linalg.inv(LAM_free))\n\n ### Step 6: Initialize Global Scattering Matrix ###\n SG = dict({})\n SG_S11 = tf.zeros(shape = (2 * np.prod(PQ), 2 * np.prod(PQ)), dtype = tf.complex64)\n SG['S11'] = tensor_utils.expand_and_tile_tf(SG_S11, batchSize, pixelsX, pixelsY)\n\n SG_S12 = tf.eye(num_rows = 2 * np.prod(PQ), dtype = tf.complex64)\n SG['S12'] = tensor_utils.expand_and_tile_tf(SG_S12, batchSize, pixelsX, pixelsY)\n\n SG_S21 = tf.eye(num_rows = 2 * np.prod(PQ), dtype = tf.complex64)\n SG['S21'] = tensor_utils.expand_and_tile_tf(SG_S21, batchSize, pixelsX, pixelsY)\n\n SG_S22 = tf.zeros(shape = (2 * np.prod(PQ), 2 * np.prod(PQ)), dtype = tf.complex64)\n SG['S22'] = tensor_utils.expand_and_tile_tf(SG_S22, batchSize, pixelsX, pixelsY)\n\n ### Step 7: Calculate eigenmodes ###\n\n # Build the eigenvalue problem.\n P_00 = tf.linalg.matmul(KX, tf.linalg.inv(ERC))\n P_00 = tf.linalg.matmul(P_00, KY)\n\n P_01 = tf.linalg.matmul(KX, tf.linalg.inv(ERC))\n P_01 = tf.linalg.matmul(P_01, KX)\n P_01 = URC - P_01\n\n P_10 = tf.linalg.matmul(KY, tf.linalg.inv(ERC))\n P_10 = tf.linalg.matmul(P_10, KY) - URC\n\n P_11 = tf.linalg.matmul(-KY, tf.linalg.inv(ERC))\n P_11 = tf.linalg.matmul(P_11, KX)\n\n P_row0 = tf.concat([P_00, P_01], axis = 5)\n P_row1 = tf.concat([P_10, P_11], axis = 5)\n P = tf.concat([P_row0, P_row1], axis = 4)\n\n Q_00 = tf.linalg.matmul(KX, tf.linalg.inv(URC))\n Q_00 = tf.linalg.matmul(Q_00, KY)\n\n Q_01 = tf.linalg.matmul(KX, tf.linalg.inv(URC))\n Q_01 = tf.linalg.matmul(Q_01, KX)\n Q_01 = ERC - Q_01\n\n Q_10 = tf.linalg.matmul(KY, tf.linalg.inv(URC))\n Q_10 = tf.linalg.matmul(Q_10, KY) - ERC\n\n Q_11 = tf.linalg.matmul(-KY, tf.linalg.inv(URC))\n Q_11 = tf.linalg.matmul(Q_11, KX)\n\n Q_row0 = tf.concat([Q_00, Q_01], axis = 5)\n Q_row1 = tf.concat([Q_10, Q_11], axis = 5)\n Q = tf.concat([Q_row0, Q_row1], axis = 4)\n\n # Compute eignmodes for the layers in each pixel for the whole batch.\n OMEGA_SQ = tf.linalg.matmul(P, Q)\n LAM, W = tensor_utils.eig_general(OMEGA_SQ)\n LAM = tf.sqrt(LAM)\n LAM = tf.linalg.diag(LAM)\n\n V = tf.linalg.matmul(Q, W)\n V = tf.linalg.matmul(V, tf.linalg.inv(LAM))\n\n # Scattering matrices for the layers in each pixel for the whole batch.\n W_inv = tf.linalg.inv(W)\n V_inv = tf.linalg.inv(V)\n A = tf.linalg.matmul(W_inv, W0) + tf.linalg.matmul(V_inv, V0)\n B = tf.linalg.matmul(W_inv, W0) - tf.linalg.matmul(V_inv, V0)\n X = tf.linalg.expm(-LAM * k0 * params['L'])\n\n S = dict({})\n A_inv = tf.linalg.inv(A)\n S11_left = tf.linalg.matmul(X, B)\n S11_left = tf.linalg.matmul(S11_left, A_inv)\n S11_left = tf.linalg.matmul(S11_left, X)\n S11_left = tf.linalg.matmul(S11_left, B)\n S11_left = A - S11_left\n S11_left = tf.linalg.inv(S11_left)\n\n S11_right = tf.linalg.matmul(X, B)\n S11_right = tf.linalg.matmul(S11_right, A_inv)\n S11_right = tf.linalg.matmul(S11_right, X)\n S11_right = tf.linalg.matmul(S11_right, A)\n S11_right = S11_right - B\n S['S11'] = tf.linalg.matmul(S11_left, S11_right)\n\n S12_right = tf.linalg.matmul(B, A_inv)\n S12_right = tf.linalg.matmul(S12_right, B)\n S12_right = A - S12_right\n S12_left = tf.linalg.matmul(S11_left, X)\n S['S12'] = tf.linalg.matmul(S12_left, S12_right)\n\n S['S21'] = S['S12']\n S['S22'] = S['S11']\n\n # Update the global scattering matrices.\n for l in range(Nlay):\n S_layer = dict({})\n S_layer['S11'] = S['S11'][:, :, :, l, :, :]\n S_layer['S12'] = S['S12'][:, :, :, l, :, :]\n S_layer['S21'] = S['S21'][:, :, :, l, :, :]\n S_layer['S22'] = S['S22'][:, :, :, l, :, :]\n SG = rcwa_utils.redheffer_star_product(SG, S_layer)\n\n ### Step 8: Reflection side ###\n # Eliminate layer dimension for tensors as they are unchanging on this dimension.\n KX = KX[:, :, :, 0, :, :]\n KY = KY[:, :, :, 0, :, :]\n KZref = KZref[:, :, :, 0, :, :]\n KZtrn = KZtrn[:, :, :, 0, :, :]\n Z = Z[:, :, :, 0, :, :]\n I = I[:, :, :, 0, :, :]\n W0 = W0[:, :, :, 0, :, :]\n V0 = V0[:, :, :, 0, :, :]\n\n Q_ref_00 = tf.linalg.matmul(KX, KY)\n Q_ref_01 = params['ur1'] * params['er1'] * I - tf.linalg.matmul(KX, KX)\n Q_ref_10 = tf.linalg.matmul(KY, KY) - params['ur1'] * params['er1'] * I\n Q_ref_11 = -tf.linalg.matmul(KY, KX)\n Q_ref_row0 = tf.concat([Q_ref_00, Q_ref_01], axis = 4)\n Q_ref_row1 = tf.concat([Q_ref_10, Q_ref_11], axis = 4)\n Q_ref = tf.concat([Q_ref_row0, Q_ref_row1], axis = 3)\n\n W_ref_row0 = tf.concat([I, Z], axis = 4)\n W_ref_row1 = tf.concat([Z, I], axis = 4)\n W_ref = tf.concat([W_ref_row0, W_ref_row1], axis = 3)\n\n LAM_ref_row0 = tf.concat([-1j * KZref, Z], axis = 4)\n LAM_ref_row1 = tf.concat([Z, -1j * KZref], axis = 4)\n LAM_ref = tf.concat([LAM_ref_row0, LAM_ref_row1], axis = 3)\n\n V_ref = tf.linalg.matmul(Q_ref, tf.linalg.inv(LAM_ref))\n\n W0_inv = tf.linalg.inv(W0)\n V0_inv = tf.linalg.inv(V0)\n A_ref = tf.linalg.matmul(W0_inv, W_ref) + tf.linalg.matmul(V0_inv, V_ref)\n A_ref_inv = tf.linalg.inv(A_ref)\n B_ref = tf.linalg.matmul(W0_inv, W_ref) - tf.linalg.matmul(V0_inv, V_ref)\n\n SR = dict({})\n SR['S11'] = tf.linalg.matmul(-A_ref_inv, B_ref)\n SR['S12'] = 2 * A_ref_inv\n SR_S21 = tf.linalg.matmul(B_ref, A_ref_inv)\n SR_S21 = tf.linalg.matmul(SR_S21, B_ref)\n SR['S21'] = 0.5 * (A_ref - SR_S21)\n SR['S22'] = tf.linalg.matmul(B_ref, A_ref_inv)\n\n ### Step 9: Transmission side ###\n Q_trn_00 = tf.linalg.matmul(KX, KY)\n Q_trn_01 = params['ur2'] * params['er2'] * I - tf.linalg.matmul(KX, KX)\n Q_trn_10 = tf.linalg.matmul(KY, KY) - params['ur2'] * params['er2'] * I\n Q_trn_11 = -tf.linalg.matmul(KY, KX)\n Q_trn_row0 = tf.concat([Q_trn_00, Q_trn_01], axis = 4)\n Q_trn_row1 = tf.concat([Q_trn_10, Q_trn_11], axis = 4)\n Q_trn = tf.concat([Q_trn_row0, Q_trn_row1], axis = 3)\n\n W_trn_row0 = tf.concat([I, Z], axis = 4)\n W_trn_row1 = tf.concat([Z, I], axis = 4)\n W_trn = tf.concat([W_trn_row0, W_trn_row1], axis = 3)\n\n LAM_trn_row0 = tf.concat([1j * KZtrn, Z], axis = 4)\n LAM_trn_row1 = tf.concat([Z, 1j * KZtrn], axis = 4)\n LAM_trn = tf.concat([LAM_trn_row0, LAM_trn_row1], axis = 3)\n\n V_trn = tf.linalg.matmul(Q_trn, tf.linalg.inv(LAM_trn))\n\n W0_inv = tf.linalg.inv(W0)\n V0_inv = tf.linalg.inv(V0)\n A_trn = tf.linalg.matmul(W0_inv, W_trn) + tf.linalg.matmul(V0_inv, V_trn)\n A_trn_inv = tf.linalg.inv(A_trn)\n B_trn = tf.linalg.matmul(W0_inv, W_trn) - tf.linalg.matmul(V0_inv, V_trn)\n\n ST = dict({})\n ST['S11'] = tf.linalg.matmul(B_trn, A_trn_inv)\n ST_S12 = tf.linalg.matmul(B_trn, A_trn_inv)\n ST_S12 = tf.linalg.matmul(ST_S12, B_trn)\n ST['S12'] = 0.5 * (A_trn - ST_S12)\n ST['S21'] = 2 * A_trn_inv\n ST['S22'] = tf.linalg.matmul(-A_trn_inv, B_trn)\n\n ### Step 10: Compute global scattering matrix ###\n SG = rcwa_utils.redheffer_star_product(SR, SG)\n SG = rcwa_utils.redheffer_star_product(SG, ST)\n\n ### Step 11: Compute source parameters ###\n\n # Compute mode coefficients of the source.\n delta = np.zeros((batchSize, pixelsX, pixelsY, np.prod(PQ)))\n delta[:, :, :, int(np.prod(PQ) / 2.0)] = 1\n\n # Incident wavevector.\n kinc_x0_pol = tf.math.real(kinc_x0[:, :, :, 0, 0])\n kinc_y0_pol = tf.math.real(kinc_y0[:, :, :, 0, 0])\n kinc_z0_pol = tf.math.real(kinc_z0[:, :, :, 0])\n kinc_pol = tf.concat([kinc_x0_pol, kinc_y0_pol, kinc_z0_pol], axis = 3)\n\n # Calculate TE and TM polarization unit vectors.\n firstPol = True\n for pol in range(batchSize):\n if (kinc_pol[pol, 0, 0, 0] == 0.0 and kinc_pol[pol, 0, 0, 1] == 0.0):\n ate_pol = np.zeros((1, pixelsX, pixelsY, 3))\n ate_pol[:, :, :, 1] = 1\n ate_pol = tf.convert_to_tensor(ate_pol, dtype = tf.float32)\n else:\n # Calculation of `ate` for oblique incidence.\n n_hat = np.zeros((1, pixelsX, pixelsY, 3))\n n_hat[:, :, :, 0] = 1\n n_hat = tf.convert_to_tensor(n_hat, dtype = tf.float32)\n kinc_pol_iter = kinc_pol[pol, :, :, :]\n kinc_pol_iter = kinc_pol_iter[tf.newaxis, :, :, :]\n ate_cross = tf.linalg.cross(n_hat, kinc_pol_iter)\n ate_pol = ate_cross / tf.norm(ate_cross, axis = 3, keepdims = True)\n\n if firstPol:\n ate = ate_pol\n firstPol = False\n else:\n ate = tf.concat([ate, ate_pol], axis = 0)\n\n atm_cross = tf.linalg.cross(kinc_pol, ate)\n atm = atm_cross / tf.norm(atm_cross, axis = 3, keepdims = True)\n ate = tf.cast(ate, dtype = tf.complex64)\n atm = tf.cast(atm, dtype = tf.complex64)\n\n # Decompose the TE and TM polarization into x and y components.\n EP = params['pte'] * ate + params['ptm'] * atm\n EP_x = EP[:, :, :, 0]\n EP_x = EP_x[:, :, :, tf.newaxis]\n EP_y = EP[:, :, :, 1]\n EP_y = EP_y[:, :, :, tf.newaxis]\n\n esrc_x = EP_x * delta\n esrc_y = EP_y * delta\n esrc = tf.concat([esrc_x, esrc_y], axis = 3)\n esrc = esrc[:, :, :, :, tf.newaxis]\n\n W_ref_inv = tf.linalg.inv(W_ref)\n\n ### Step 12: Compute reflected and transmitted fields ###\n csrc = tf.linalg.matmul(W_ref_inv, esrc)\n\n # Compute tranmission and reflection mode coefficients.\n cref = tf.linalg.matmul(SG['S11'], csrc)\n ctrn = tf.linalg.matmul(SG['S21'], csrc)\n eref = tf.linalg.matmul(W_ref, cref)\n etrn = tf.linalg.matmul(W_trn, ctrn)\n\n rx = eref[:, :, :, 0 : np.prod(PQ), :]\n ry = eref[:, :, :, np.prod(PQ) : 2 * np.prod(PQ), :]\n tx = etrn[:, :, :, 0 : np.prod(PQ), :]\n ty = etrn[:, :, :, np.prod(PQ) : 2 * np.prod(PQ), :]\n\n # Compute longitudinal components.\n KZref_inv = tf.linalg.inv(KZref)\n KZtrn_inv = tf.linalg.inv(KZtrn)\n rz = tf.linalg.matmul(KX, rx) + tf.linalg.matmul(KY, ry)\n rz = tf.linalg.matmul(-KZref_inv, rz)\n tz = tf.linalg.matmul(KX, tx) + tf.linalg.matmul(KY, ty)\n tz = tf.linalg.matmul(-KZtrn_inv, tz)\n\n ### Step 13: Compute diffraction efficiences ###\n rx2 = tf.math.real(rx) ** 2 + tf.math.imag(rx) ** 2\n ry2 = tf.math.real(ry) ** 2 + tf.math.imag(ry) ** 2\n rz2 = tf.math.real(rz) ** 2 + tf.math.imag(rz) ** 2\n R2 = rx2 + ry2 + rz2\n R = tf.math.real(-KZref / params['ur1']) / tf.math.real(kinc_z0 / params['ur1'])\n R = tf.linalg.matmul(R, R2)\n R = tf.reshape(R, shape = (batchSize, pixelsX, pixelsY, PQ[0], PQ[1]))\n REF = tf.math.reduce_sum(R, axis = [3, 4])\n\n tx2 = tf.math.real(tx) ** 2 + tf.math.imag(tx) ** 2\n ty2 = tf.math.real(ty) ** 2 + tf.math.imag(ty) ** 2\n tz2 = tf.math.real(tz) ** 2 + tf.math.imag(tz) ** 2\n T2 = tx2 + ty2 + tz2\n T = tf.math.real(KZtrn / params['ur2']) / tf.math.real(kinc_z0 / params['ur2'])\n T = tf.linalg.matmul(T, T2)\n T = tf.reshape(T, shape = (batchSize, pixelsX, pixelsY, PQ[0], PQ[1]))\n TRN = tf.math.reduce_sum(T, axis = [3, 4])\n\n # Store the transmission/reflection coefficients and powers in a dictionary.\n outputs = dict({})\n outputs['rx'] = rx\n outputs['ry'] = ry\n outputs['rz'] = rz\n outputs['R'] = R\n outputs['REF'] = REF\n outputs['tx'] = tx\n outputs['ty'] = ty\n outputs['tz'] = tz\n outputs['T'] = T\n outputs['TRN'] = TRN\n\n return outputs\n" ]
[ [ "tensorflow.exp", "tensorflow.image.resize_with_crop_or_pad", "tensorflow.ones", "tensorflow.signal.ifftshift", "tensorflow.reshape", "numpy.mean", "tensorflow.linalg.cross", "tensorflow.sqrt", "tensorflow.clip_by_value", "tensorflow.math.sqrt", "tensorflow.tile", "tensorflow.signal.ifft2d", "tensorflow.cast", "tensorflow.square", "numpy.sin", "tensorflow.concat", "tensorflow.math.reduce_sum", "tensorflow.linalg.inv", "tensorflow.transpose", "tensorflow.math.abs", "tensorflow.norm", "numpy.prod", "numpy.transpose", "numpy.sqrt", "tensorflow.math.real", "tensorflow.abs", "tensorflow.zeros", "numpy.zeros", "tensorflow.math.sigmoid", "numpy.round", "tensorflow.cos", "tensorflow.linalg.matmul", "tensorflow.math.conj", "tensorflow.sin", "numpy.hstack", "numpy.floor", "tensorflow.linalg.expm", "tensorflow.convert_to_tensor", "tensorflow.linalg.diag", "tensorflow.math.imag", "numpy.ones", "numpy.linspace", "tensorflow.signal.fft2d", "tensorflow.image.resize", "numpy.meshgrid" ] ]
ZiGaMi/StewardPlatformEvaluation
[ "9995507ec70156ec950fc79a388cfcd08ab7e65a" ]
[ "simulation/human_perception.py" ]
[ "# ===============================================================================\n# @file: human_perception.py\n# @note: This script is for model design of human perception of movement \n# @author: Ziga Miklosic\n# @date: 13.01.2021\n# @brief: Evaluation of human movement perception model base on \n# \"Vehicle modelling and washout filter tuning for the Chalmers Vehicle\n# Simulator\" thesis.\n# ===============================================================================\n\n\n# ===============================================================================\n# IMPORTS \n# ===============================================================================\nimport sys\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.signal import freqz, bilinear\n\nfrom filters.filter_utils import FunctionGenerator\nfrom filters.iir_filter import IIR\n\n# ===============================================================================\n# CONSTANTS\n# ===============================================================================\n\n## ****** USER CONFIGURATIONS ******\n\n## Sample frequency\n# Sample frequency of real system \n#\n# Unit: Hz\nSAMPLE_FREQ = 100.0\n\n# Ideal sample frequency\n# As a reference to sample rate constrained embedded system\n#\n# Unit: Hz\nIDEAL_SAMPLE_FREQ = 1000.0\n\n## Time window\n#\n# Unit: second\nTIME_WINDOW = 10\n\n## Input signal shape\nINPUT_SIGNAL_FREQ = 0.1\nINPUT_SIGNAL_AMPLITUDE = 9.81/4\nINPUT_SIGNAL_OFFSET = INPUT_SIGNAL_AMPLITUDE\nINPUT_SIGNAL_PHASE = -0.25\n\n## Mux input signal\nINPUT_SIGNAL_SELECTION = FunctionGenerator.FG_KIND_RECT\n\n## Number of samples in time window\nSAMPLE_NUM = int(( IDEAL_SAMPLE_FREQ * TIME_WINDOW ) + 1.0 )\n\n\n## Parameters of the vestibular system\nVESTIBULAR_ROLL_TL = 6.1\nVESTIBULAR_ROLL_TS = 0.1\nVESTIBULAR_ROLL_TA = 30.0\n\nVESTIBULAR_PITCH_TL = 5.3\nVESTIBULAR_PITCH_TS = 0.1\nVESTIBULAR_PITCH_TA = 30.0\n\nVESTIBULAR_YAW_TL = 10.2\nVESTIBULAR_YAW_TS = 0.1\nVESTIBULAR_YAW_TA = 30.0\n\nVESTIBULAR_X_TL = 5.33\nVESTIBULAR_X_TS = 0.66\nVESTIBULAR_X_TA = 13.2\nVESTIBULAR_X_K = 0.4\n\nVESTIBULAR_Y_TL = 5.33\nVESTIBULAR_Y_TS = 0.66\nVESTIBULAR_Y_TA = 13.2\nVESTIBULAR_Y_K = 0.4\n\nVESTIBULAR_Z_TL = 5.33\nVESTIBULAR_Z_TS = 0.66\nVESTIBULAR_Z_TA = 13.2\nVESTIBULAR_Z_K = 0.4\n\n\n\n\n## ****** END OF USER CONFIGURATIONS ******\n\n# ===============================================================================\n# FUNCTIONS\n# ===============================================================================\n\n\n# ===============================================================================\n# @brief: Calculate rotation perception coefficients\n# \n# h(s) = (1/Ts * s^2) / ( s^3 + (1/Ta + 1/Tl + 1/Ts)*s^2 + (1/Tl*Ts + 1/Tl*Ta + 1/Ta*Ts)*s + 1/(Ta*Tl*Ts)))\n#\n# @param[in]: Tl, Ts, Ta - Coefficient in the semicircular canals sensation model\n# @param[in]: fs - Sample frequency\n# @return: b,a - Array of b,a IIR coefficients\n# ===============================================================================\ndef calc_rot_mov_coefficient(Tl, Ts, Ta, fs):\n\n b, a = bilinear( [0, 1/Ts, 0, 0], [1, (1/Ta + 1/Tl + 1/Ts), (1/Tl*Ts + 1/Tl*Ta + 1/Ta*Ts), 1/(Ta*Tl*Ts)], fs )\n\n return b, a\n\n\n# ===============================================================================\n# @brief: Calculate linear movement perception coefficients\n# \n# h(s) = ((K*Ta/(Tl*Ts))*s + (K*Ta/(Tl*Ts))) / ( s^2 + (1/Tl + 1/Ts)*s + 1/(Tl*Ts))\n#\n# @param[in]: Tl, Ts, Ta, K - Coefficients in the otolith model\n# @param[in]: fs - Sample frequency\n# @return: b,a - Array of b,a IIR coefficients\n# ===============================================================================\ndef calc_lin_mov_coefficient(Tl, Ts, Ta, K, fs):\n\n b, a = bilinear( [0, K*Ta, K], [ Tl*Ts, Tl+Ts, 1], fs )\n\n return b, a\n\n# ===============================================================================\n# CLASSES\n# =============================================================================== \n\n## Vestibular system\nclass VestibularSystem:\n\n # ===============================================================================\n # @brief: Init vestibular system\n # \n # @return: void\n # ===============================================================================\n def __init__(self):\n\n ## Parameters of the vestibular system\n VESTIBULAR_ROLL_TL = 6.1\n VESTIBULAR_ROLL_TS = 0.1\n VESTIBULAR_ROLL_TA = 30.0\n\n VESTIBULAR_PITCH_TL = 5.3\n VESTIBULAR_PITCH_TS = 0.1\n VESTIBULAR_PITCH_TA = 30.0\n\n VESTIBULAR_YAW_TL = 10.2\n VESTIBULAR_YAW_TS = 0.1\n VESTIBULAR_YAW_TA = 30.0\n\n VESTIBULAR_X_TL = 5.33\n VESTIBULAR_X_TS = 0.66\n VESTIBULAR_X_TA = 13.2\n VESTIBULAR_X_K = 0.4\n\n VESTIBULAR_Y_TL = 5.33\n VESTIBULAR_Y_TS = 0.66\n VESTIBULAR_Y_TA = 13.2\n VESTIBULAR_Y_K = 0.4\n\n VESTIBULAR_Z_TL = 5.33\n VESTIBULAR_Z_TS = 0.66\n VESTIBULAR_Z_TA = 13.2\n VESTIBULAR_Z_K = 0.4\n\n # Rotation movement coefficient\n _roll_b, _roll_a = self.__calc_rot_mov_coefficient( VESTIBULAR_ROLL_TL, VESTIBULAR_ROLL_TS, VESTIBULAR_ROLL_TA, SAMPLE_FREQ )\n _pitch_b, _pitch_a = self.__calc_rot_mov_coefficient( VESTIBULAR_PITCH_TL, VESTIBULAR_PITCH_TS, VESTIBULAR_PITCH_TA, SAMPLE_FREQ )\n _yaw_b, _yaw_a = self.__calc_rot_mov_coefficient( VESTIBULAR_YAW_TL, VESTIBULAR_YAW_TS, VESTIBULAR_YAW_TA, SAMPLE_FREQ )\n\n # Linear movement coefficient\n _x_b, _x_a = self.__calc_lin_mov_coefficient( VESTIBULAR_X_TL, VESTIBULAR_X_TS, VESTIBULAR_X_TA, VESTIBULAR_X_K, SAMPLE_FREQ )\n _y_b, _y_a = self.__calc_lin_mov_coefficient( VESTIBULAR_Y_TL, VESTIBULAR_Y_TS, VESTIBULAR_Y_TA, VESTIBULAR_Y_K, SAMPLE_FREQ )\n _z_b, _z_a = self.__calc_lin_mov_coefficient( VESTIBULAR_Z_TL, VESTIBULAR_Z_TS, VESTIBULAR_Z_TA, VESTIBULAR_Z_K, SAMPLE_FREQ )\n\n self._roll_filt = IIR( a=_roll_a, b=_roll_b, order=3 )\n self._pitch_filt = IIR( a=_pitch_a, b=_pitch_b, order=3 )\n self._yaw_filt = IIR( a=_yaw_a, b=_yaw_b, order=3 )\n\n self._x_filt = IIR( a=_x_a, b=_x_b, order=2 )\n self._y_filt = IIR( a=_y_a, b=_y_b, order=2 )\n self._z_filt = IIR( a=_z_a, b=_z_b, order=2 )\n\n # ===============================================================================\n # @brief: Update vesticular system\n # \n #\n # @param[in]: a - Input accelerations\n # @param[in]: w - Input angular velocities\n # @return: af, wf - Sensed accelerations and angular velocities\n # ===============================================================================\n def update(self, a, w):\n \n af_x = self._x_filt.update( a[0] ) \n af_y = self._y_filt.update( a[1] ) \n af_z = self._z_filt.update( a[2] ) \n af = [af_x, af_y, af_z]\n\n wf_x = self._roll_filt.update( w[0] ) \n wf_y = self._pitch_filt.update( w[1] ) \n wf_z = self._yaw_filt.update( w[2] ) \n wf = [wf_x, wf_y, wf_z]\n\n return af, wf\n\n # ===============================================================================\n # @brief: Calculate rotation perception coefficients\n # \n # h(s) = (1/Ts * s^2) / ( s^3 + (1/Ta + 1/Tl + 1/Ts)*s^2 + (1/Tl*Ts + 1/Tl*Ta + 1/Ta*Ts)*s + 1/(Ta*Tl*Ts)))\n #\n # @param[in]: Tl, Ts, Ta - Coefficient in the semicircular canals sensation model\n # @param[in]: fs - Sample frequency\n # @return: b,a - Array of b,a IIR coefficients\n # ===============================================================================\n def __calc_rot_mov_coefficient(self, Tl, Ts, Ta, fs):\n\n b, a = bilinear( [0, 1/Ts, 0, 0], [1, (1/Ta + 1/Tl + 1/Ts), (1/Tl*Ts + 1/Tl*Ta + 1/Ta*Ts), 1/(Ta*Tl*Ts)], fs )\n\n return b, a\n\n\n # ===============================================================================\n # @brief: Calculate linear movement perception coefficients\n # \n # h(s) = ((K*Ta)*s + k) / ((Tl*Ts)*s^2 + (Tl+Ts)*s + 1)\n #\n # @param[in]: Tl, Ts, Ta, K - Coefficients in the otolith model\n # @param[in]: fs - Sample frequency\n # @return: b,a - Array of b,a IIR coefficients\n # ===============================================================================\n def __calc_lin_mov_coefficient(self, Tl, Ts, Ta, K, fs):\n\n b, a = bilinear( [0, K*Ta, K], [ Tl*Ts, Tl+Ts, 1], fs )\n\n return b, a\n\n\n# ===============================================================================\n# MAIN ENTRY\n# ===============================================================================\nif __name__ == \"__main__\":\n\n # Time array\n _time, _dt = np.linspace( 0.0, TIME_WINDOW, num=SAMPLE_NUM, retstep=True )\n\n \n # Rotation movement coefficient\n _roll_b, _roll_a = calc_rot_mov_coefficient( VESTIBULAR_ROLL_TL, VESTIBULAR_ROLL_TS, VESTIBULAR_ROLL_TA, SAMPLE_FREQ )\n _pitch_b, _pitch_a = calc_rot_mov_coefficient( VESTIBULAR_PITCH_TL, VESTIBULAR_PITCH_TS, VESTIBULAR_PITCH_TA, SAMPLE_FREQ )\n _yaw_b, _yaw_a = calc_rot_mov_coefficient( VESTIBULAR_YAW_TL, VESTIBULAR_YAW_TS, VESTIBULAR_YAW_TA, SAMPLE_FREQ )\n\n # Linear movement coefficient\n _x_b, _x_a = calc_lin_mov_coefficient( VESTIBULAR_X_TL, VESTIBULAR_X_TS, VESTIBULAR_X_TA, VESTIBULAR_X_K, SAMPLE_FREQ )\n _y_b, _y_a = calc_lin_mov_coefficient( VESTIBULAR_Y_TL, VESTIBULAR_Y_TS, VESTIBULAR_Y_TA, VESTIBULAR_Y_K, SAMPLE_FREQ )\n _z_b, _z_a = calc_lin_mov_coefficient( VESTIBULAR_Z_TL, VESTIBULAR_Z_TS, VESTIBULAR_Z_TA, VESTIBULAR_Z_K, SAMPLE_FREQ )\n\n # Filters\n _roll_filt = IIR( a=_roll_a, b=_roll_b, order=3 )\n _pitch_filt = IIR( a=_pitch_a, b=_pitch_b, order=3 )\n _yaw_filt = IIR( a=_yaw_a, b=_yaw_b, order=3 )\n\n _x_filt = IIR( a=_x_a, b=_x_b, order=2 )\n\n # Get frequency characteristics\n N = 256\n _roll_w, _roll_h = freqz( _roll_b, _roll_a, 4096 * N )\n #_pitch_w, _pitch_h = freqz( _pitch_b, _pitch_a, 4096 * N )\n #_yaw_w, _yaw_h = freqz( _yaw_b, _yaw_a, 4096 * N )\n\n _x_w, _x_h = freqz( _x_b, _x_a, 4096 * N )\n #_y_w, _y_h = freqz( _y_b, _y_a, 4096 * N )\n #_z_w, _z_h = freqz( _z_b, _z_a, 4096 * N )\n\n\n # Vestibular system\n _vest_sys = VestibularSystem()\n\n\n\n # Filter input/output\n _x = [ 0 ] * SAMPLE_NUM\n _x_d = [0]\n\n \n _y_d_roll = [0]\n _y_d_x = [0]\n \n\n # Accelerations\n _y_d_a_sens = [[0], [0], [0]] * 3\n \n # Angular rates\n _y_d_w_sens = [[0], [0], [0]] * 3\n\n # Generate inputs\n _fg = FunctionGenerator( INPUT_SIGNAL_FREQ, INPUT_SIGNAL_AMPLITUDE, INPUT_SIGNAL_OFFSET, INPUT_SIGNAL_PHASE, INPUT_SIGNAL_SELECTION )\n \n # Down sample\n _downsamp_cnt = 0\n _downsamp_samp = [0]\n _d_time = [0]\n \n # Generate stimuli signals\n for n in range(SAMPLE_NUM):\n #_x[n] = ( _fg.generate( _time[n] ))\n \n\n # Some custom signal\n \n if _time[n] < 1.0:\n _x[n] = 0.0\n elif _time[n] < 2.0:\n _x[n] = _x[n-1] + 0.5 / IDEAL_SAMPLE_FREQ\n elif _time[n] < 3.0:\n _x[n] = 0.5\n elif _time[n] < 4.0:\n _x[n] = _x[n-1] - 0.5 / IDEAL_SAMPLE_FREQ\n elif _time[n] < 10.0:\n _x[n] = 0\n else:\n _x[n] = 0\n \n\n\n # Apply filter\n for n in range(SAMPLE_NUM):\n \n # Mux input signals\n #_x[n] = _signa_mux.out( INPUT_SIGNAL_SELECTION, [ _sin_x[n], _rect_x[n] ] )\n\n # Down sample to SAMPLE_FREQ\n if _downsamp_cnt >= (( 1 / ( _dt * SAMPLE_FREQ )) - 1 ):\n _downsamp_cnt = 0\n\n # Utils\n _downsamp_samp.append(0)\n _d_time.append( _time[n])\n _x_d.append( _x[n] )\n\n \n # Rotation sensed\n _y_d_roll.append( _roll_filt.update( _x[n] ))\n _y_d_x.append( _x_filt.update( _x[n] ))\n \n\n a_sens, w_sens = _vest_sys.update( [ _x[n], 0, 0 ], [ _x[n], 0, 0 ] )\n\n for n in range(3):\n _y_d_a_sens[n].append( a_sens[n] )\n _y_d_w_sens[n].append( w_sens[n] )\n else:\n _downsamp_cnt += 1\n \n\n # Calculate frequency response\n _roll_w = ( _roll_w / np.pi * SAMPLE_FREQ / 2) # Hz\n #_pitch_w = ( _pitch_w / np.pi * SAMPLE_FREQ / 2) # Hz\n #_yaw_w = ( _yaw_w / np.pi * SAMPLE_FREQ / 2) # Hz\n\n _x_w = ( _x_w / np.pi * SAMPLE_FREQ / 2) # Hz\n #_y_w = ( _y_w / np.pi * SAMPLE_FREQ / 2) # Hz\n #_z_w = ( _z_w / np.pi * SAMPLE_FREQ / 2) # Hz\n\n # For conversion to rad/s\n _roll_w = 2*np.pi*_roll_w \n #_pitch_w = 2*np.pi*_pitch_w \n #_yaw_w = 2*np.pi*_yaw_w \n\n _x_w = 2*np.pi*_x_w \n #_y_w = 2*np.pi*_y_w \n #_z_w = 2*np.pi*_z_w \n\n # Calculate phases & convert to degrees\n _roll_angle = np.unwrap( np.angle(_roll_h) ) * 180/np.pi\n #_pitch_angle = np.unwrap( np.angle(_pitch_h) ) * 180/np.pi\n #_yaw_angle = np.unwrap( np.angle(_yaw_h) ) * 180/np.pi\n\n _x_angle = np.unwrap( np.angle(_x_h) ) * 180/np.pi\n #_y_angle = np.unwrap( np.angle(_y_h) ) * 180/np.pi\n #_z_angle = np.unwrap( np.angle(_z_h) ) * 180/np.pi\n\n \n\n plt.style.use(['dark_background'])\n ## ==============================================================================================\n # Rotation motion plots\n ## ==============================================================================================\n fig, ax = plt.subplots(2, 1)\n fig.suptitle( \"ROTATION MOVEMENT MODEL\\n fs: \" + str(SAMPLE_FREQ) + \"Hz\", fontsize=16 )\n\n \n ax[0].plot(_roll_w, 20 * np.log10(abs(_roll_h)), \"w\")\n\n ax[0].grid(alpha=0.25)\n ax[0].set_xscale(\"log\")\n ax[0].set_xlim(1e-3, SAMPLE_FREQ/2)\n ax[0].set_ylim(-80, 2)\n ax[0].set_ylabel(\"Magnitude [dB]\", color=\"w\", fontsize=14)\n ax[0].set_xlabel(\"Frequency [rad/s]\", fontsize=14)\n\n ax_00 = ax[0].twinx()\n\n ax_00.plot(_roll_w, _roll_angle, \"r\")\n ax_00.set_ylabel(\"Phase [deg]\", color=\"r\", fontsize=14)\n ax_00.set_xscale(\"log\")\n ax_00.grid(alpha=0.25)\n ax_00.set_xlim(1e-3, SAMPLE_FREQ/2)\n ax_00.set_xlabel(\"Frequency [rad/s]\", fontsize=14)\n \n\n ax[1].plot( _time, _x, \"r\", label=\"Input\" )\n ax[1].plot( _d_time, _y_d_roll, \".-y\", label=\"Sensed\")\n ax[1].plot( _d_time, _y_d_w_sens[0], \"--w\", label=\"Sensed\")\n ax[1].grid(alpha=0.25)\n ax[1].set_xlim(0, 8)\n ax[1].legend(loc=\"upper right\")\n ax[1].grid(alpha=0.25)\n ax[1].set_xlabel(\"Time [s]\", fontsize=14)\n ax[1].set_ylabel(\"rotation, sensed rotation [rad/s]\", fontsize=14)\n\n ## ==============================================================================================\n # Linear motion plots\n ## ==============================================================================================\n fig, ax = plt.subplots(2, 1)\n fig.suptitle( \"LINEAR MOVEMENT MODEL\\n fs: \" + str(SAMPLE_FREQ) + \"Hz\", fontsize=16 )\n\n \n ax[0].plot(_x_w, 20 * np.log10(abs(_x_h)), 'w')\n ax[0].grid(alpha=0.25)\n ax[0].set_xscale(\"log\")\n ax[0].set_xlim(1e-3, SAMPLE_FREQ/2)\n ax[0].set_ylim(-40, 1)\n ax[0].set_ylabel(\"Magnitude [dB]\", color=\"w\", fontsize=14)\n ax[0].set_xlabel(\"Frequency [rad/s]\", fontsize=14)\n\n ax_00 = ax[0].twinx()\n\n ax_00.plot(_x_w, _x_angle, \"r\")\n\n ax_00.set_ylabel(\"Phase [deg]\", color=\"r\", fontsize=14)\n ax_00.set_xscale(\"log\")\n ax_00.grid(alpha=0.25)\n ax_00.set_xlim(1e-3, SAMPLE_FREQ/2)\n ax_00.set_xlabel(\"Frequency [rad/s]\")\n \n\n\n ax[1].plot( _time, _x, \"r\", label=\"Input\" )\n ax[1].plot( _d_time, _y_d_x, \".-y\", label=\"Sensed\")\n ax[1].plot( _d_time, _y_d_a_sens[0], \"--w\", label=\"Sensed\")\n ax[1].grid(alpha=0.25)\n ax[1].set_xlim(0, 8)\n ax[1].legend(loc=\"upper right\")\n ax[1].grid(alpha=0.25)\n ax[1].set_xlabel(\"Time [s]\", fontsize=14)\n ax[1].set_ylabel(\"acceleration, sensed force [mm^2]\", fontsize=14)\n\n plt.show()\n \n\n\n# ===============================================================================\n# END OF FILE\n# ===============================================================================\n" ]
[ [ "numpy.angle", "scipy.signal.bilinear", "matplotlib.pyplot.subplots", "matplotlib.pyplot.style.use", "scipy.signal.freqz", "matplotlib.pyplot.show", "numpy.linspace" ] ]
raznem/RL_cs294
[ "e671e8ad602e58adcae44fbed8aaaf39942a1dbc" ]
[ "hw3/dqn_utils.py" ]
[ "\"\"\"This file includes a collection of utility functions that are useful for\nimplementing DQN.\"\"\"\nimport gym\nimport tensorflow as tf\nimport numpy as np\nimport random\n\ndef huber_loss(x, delta=1.0):\n # https://en.wikipedia.org/wiki/Huber_loss\n return tf.where(\n tf.abs(x) < delta,\n tf.square(x) * 0.5,\n delta * (tf.abs(x) - 0.5 * delta)\n )\n\ndef sample_n_unique(sampling_f, n):\n \"\"\"Helper function. Given a function `sampling_f` that returns\n comparable objects, sample n such unique objects.\n \"\"\"\n res = []\n while len(res) < n:\n candidate = sampling_f()\n if candidate not in res:\n res.append(candidate)\n return res\n\nclass Schedule(object):\n def value(self, t):\n \"\"\"Value of the schedule at time t\"\"\"\n raise NotImplementedError()\n\nclass ConstantSchedule(object):\n def __init__(self, value):\n \"\"\"Value remains constant over time.\n Parameters\n ----------\n value: float\n Constant value of the schedule\n \"\"\"\n self._v = value\n\n def value(self, t):\n \"\"\"See Schedule.value\"\"\"\n return self._v\n\ndef linear_interpolation(l, r, alpha):\n return l + alpha * (r - l)\n\nclass PiecewiseSchedule(object):\n def __init__(self, endpoints, interpolation=linear_interpolation, outside_value=None):\n \"\"\"Piecewise schedule.\n endpoints: [(int, int)]\n list of pairs `(time, value)` meanining that schedule should output\n `value` when `t==time`. All the values for time must be sorted in\n an increasing order. When t is between two times, e.g. `(time_a, value_a)`\n and `(time_b, value_b)`, such that `time_a <= t < time_b` then value outputs\n `interpolation(value_a, value_b, alpha)` where alpha is a fraction of\n time passed between `time_a` and `time_b` for time `t`.\n interpolation: lambda float, float, float: float\n a function that takes value to the left and to the right of t according\n to the `endpoints`. Alpha is the fraction of distance from left endpoint to\n right endpoint that t has covered. See linear_interpolation for example.\n outside_value: float\n if the value is requested outside of all the intervals sepecified in\n `endpoints` this value is returned. If None then AssertionError is\n raised when outside value is requested.\n \"\"\"\n idxes = [e[0] for e in endpoints]\n assert idxes == sorted(idxes)\n self._interpolation = interpolation\n self._outside_value = outside_value\n self._endpoints = endpoints\n\n def value(self, t):\n \"\"\"See Schedule.value\"\"\"\n for (l_t, l), (r_t, r) in zip(self._endpoints[:-1], self._endpoints[1:]):\n if l_t <= t and t < r_t:\n alpha = float(t - l_t) / (r_t - l_t)\n return self._interpolation(l, r, alpha)\n\n # t does not belong to any of the pieces, so doom.\n assert self._outside_value is not None\n return self._outside_value\n\nclass LinearSchedule(object):\n def __init__(self, schedule_timesteps, final_p, initial_p=1.0):\n \"\"\"Linear interpolation between initial_p and final_p over\n schedule_timesteps. After this many timesteps pass final_p is\n returned.\n Parameters\n ----------\n schedule_timesteps: int\n Number of timesteps for which to linearly anneal initial_p\n to final_p\n initial_p: float\n initial output value\n final_p: float\n final output value\n \"\"\"\n self.schedule_timesteps = schedule_timesteps\n self.final_p = final_p\n self.initial_p = initial_p\n\n def value(self, t):\n \"\"\"See Schedule.value\"\"\"\n fraction = min(float(t) / self.schedule_timesteps, 1.0)\n return self.initial_p + fraction * (self.final_p - self.initial_p)\n\ndef compute_exponential_averages(variables, decay):\n \"\"\"Given a list of tensorflow scalar variables\n create ops corresponding to their exponential\n averages\n Parameters\n ----------\n variables: [tf.Tensor]\n List of scalar tensors.\n Returns\n -------\n averages: [tf.Tensor]\n List of scalar tensors corresponding to averages\n of al the `variables` (in order)\n apply_op: tf.runnable\n Op to be run to update the averages with current value\n of variables.\n \"\"\"\n averager = tf.train.ExponentialMovingAverage(decay=decay)\n apply_op = averager.apply(variables)\n return [averager.average(v) for v in variables], apply_op\n\ndef minimize_and_clip(optimizer, objective, var_list, clip_val=10):\n \"\"\"Minimized `objective` using `optimizer` w.r.t. variables in\n `var_list` while ensure the norm of the gradients for each\n variable is clipped to `clip_val`\n \"\"\"\n gradients = optimizer.compute_gradients(objective, var_list=var_list)\n for i, (grad, var) in enumerate(gradients):\n if grad is not None:\n gradients[i] = (tf.clip_by_norm(grad, clip_val), var)\n return optimizer.apply_gradients(gradients)\n\ndef initialize_interdependent_variables(session, vars_list, feed_dict):\n \"\"\"Initialize a list of variables one at a time, which is useful if\n initialization of some variables depends on initialization of the others.\n \"\"\"\n vars_left = vars_list\n while len(vars_left) > 0:\n new_vars_left = []\n for v in vars_left:\n try:\n # If using an older version of TensorFlow, uncomment the line\n # below and comment out the line after it.\n\t\t#session.run(tf.initialize_variables([v]), feed_dict)\n session.run(tf.variables_initializer([v]), feed_dict)\n except tf.errors.FailedPreconditionError:\n new_vars_left.append(v)\n if len(new_vars_left) >= len(vars_left):\n # This can happend if the variables all depend on each other, or more likely if there's\n # another variable outside of the list, that still needs to be initialized. This could be\n # detected here, but life's finite.\n raise Exception(\"Cycle in variable dependencies, or external precondition unsatisfied.\")\n else:\n vars_left = new_vars_left\n\ndef get_wrapper_by_name(env, classname):\n currentenv = env\n while True:\n if classname in currentenv.__class__.__name__:\n return currentenv\n elif isinstance(env, gym.Wrapper):\n currentenv = currentenv.env\n else:\n raise ValueError(\"Couldn't find wrapper named %s\"%classname)\n\nclass ReplayBuffer(object):\n def __init__(self, size, frame_history_len, lander=False):\n \"\"\"This is a memory efficient implementation of the replay buffer.\n\n The sepecific memory optimizations use here are:\n - only store each frame once rather than k times\n even if every observation normally consists of k last frames\n - store frames as np.uint8 (actually it is most time-performance\n to cast them back to float32 on GPU to minimize memory transfer\n time)\n - store frame_t and frame_(t+1) in the same buffer.\n\n For the tipical use case in Atari Deep RL buffer with 1M frames the total\n memory footprint of this buffer is 10^6 * 84 * 84 bytes ~= 7 gigabytes\n\n Warning! Assumes that returning frame of zeros at the beginning\n of the episode, when there is less frames than `frame_history_len`,\n is acceptable.\n\n Parameters\n ----------\n size: int\n Max number of transitions to store in the buffer. When the buffer\n overflows the old memories are dropped.\n frame_history_len: int\n Number of memories to be retried for each observation.\n \"\"\"\n self.lander = lander\n\n self.size = size\n self.frame_history_len = frame_history_len\n\n self.next_idx = 0\n self.num_in_buffer = 0\n\n self.obs = None\n self.action = None\n self.reward = None\n self.done = None\n\n def can_sample(self, batch_size):\n \"\"\"Returns true if `batch_size` different transitions can be sampled from the buffer.\"\"\"\n return batch_size + 1 <= self.num_in_buffer\n\n def _encode_sample(self, idxes):\n obs_batch = np.concatenate([self._encode_observation(idx)[None] for idx in idxes], 0)\n act_batch = self.action[idxes]\n rew_batch = self.reward[idxes]\n next_obs_batch = np.concatenate([self._encode_observation(idx + 1)[None] for idx in idxes], 0)\n done_mask = np.array([1.0 if self.done[idx] else 0.0 for idx in idxes], dtype=np.float32)\n\n return obs_batch, act_batch, rew_batch, next_obs_batch, done_mask\n\n\n def sample(self, batch_size):\n \"\"\"Sample `batch_size` different transitions.\n\n i-th sample transition is the following:\n\n when observing `obs_batch[i]`, action `act_batch[i]` was taken,\n after which reward `rew_batch[i]` was received and subsequent\n observation next_obs_batch[i] was observed, unless the epsiode\n was done which is represented by `done_mask[i]` which is equal\n to 1 if episode has ended as a result of that action.\n\n Parameters\n ----------\n batch_size: int\n How many transitions to sample.\n\n Returns\n -------\n obs_batch: np.array\n Array of shape\n (batch_size, img_h, img_w, img_c * frame_history_len)\n and dtype np.uint8\n act_batch: np.array\n Array of shape (batch_size,) and dtype np.int32\n rew_batch: np.array\n Array of shape (batch_size,) and dtype np.float32\n next_obs_batch: np.array\n Array of shape\n (batch_size, img_h, img_w, img_c * frame_history_len)\n and dtype np.uint8\n done_mask: np.array\n Array of shape (batch_size,) and dtype np.float32\n \"\"\"\n assert self.can_sample(batch_size)\n idxes = sample_n_unique(lambda: random.randint(0, self.num_in_buffer - 2), batch_size)\n return self._encode_sample(idxes)\n\n def encode_recent_observation(self):\n \"\"\"Return the most recent `frame_history_len` frames.\n\n Returns\n -------\n observation: np.array\n Array of shape (img_h, img_w, img_c * frame_history_len)\n and dtype np.uint8, where observation[:, :, i*img_c:(i+1)*img_c]\n encodes frame at time `t - frame_history_len + i`\n \"\"\"\n assert self.num_in_buffer > 0\n return self._encode_observation((self.next_idx - 1) % self.size)\n\n def _encode_observation(self, idx):\n end_idx = idx + 1 # make noninclusive\n start_idx = end_idx - self.frame_history_len\n # this checks if we are using low-dimensional observations, such as RAM\n # state, in which case we just directly return the latest RAM.\n if len(self.obs.shape) == 2:\n return self.obs[end_idx-1]\n # if there weren't enough frames ever in the buffer for context\n if start_idx < 0 and self.num_in_buffer != self.size:\n start_idx = 0\n for idx in range(start_idx, end_idx - 1):\n if self.done[idx % self.size]:\n start_idx = idx + 1\n missing_context = self.frame_history_len - (end_idx - start_idx)\n # if zero padding is needed for missing context\n # or we are on the boundry of the buffer\n if start_idx < 0 or missing_context > 0:\n frames = [np.zeros_like(self.obs[0]) for _ in range(missing_context)]\n for idx in range(start_idx, end_idx):\n frames.append(self.obs[idx % self.size])\n return np.concatenate(frames, 2)\n else:\n # this optimization has potential to saves about 30% compute time \\o/\n img_h, img_w = self.obs.shape[1], self.obs.shape[2]\n return self.obs[start_idx:end_idx].transpose(1, 2, 0, 3).reshape(img_h, img_w, -1)\n\n def store_frame(self, frame):\n \"\"\"Store a single frame in the buffer at the next available index, overwriting\n old frames if necessary.\n\n Parameters\n ----------\n frame: np.array\n Array of shape (img_h, img_w, img_c) and dtype np.uint8\n the frame to be stored\n\n Returns\n -------\n idx: int\n Index at which the frame is stored. To be used for `store_effect` later.\n \"\"\"\n if self.obs is None:\n self.obs = np.empty([self.size] + list(frame.shape), dtype=np.float32 if self.lander else np.uint8)\n self.action = np.empty([self.size], dtype=np.int32)\n self.reward = np.empty([self.size], dtype=np.float32)\n self.done = np.empty([self.size], dtype=np.bool)\n self.obs[self.next_idx] = frame\n\n ret = self.next_idx\n self.next_idx = (self.next_idx + 1) % self.size\n self.num_in_buffer = min(self.size, self.num_in_buffer + 1)\n\n return ret\n\n def store_effect(self, idx, action, reward, done):\n \"\"\"Store effects of action taken after obeserving frame stored\n at index idx. The reason `store_frame` and `store_effect` is broken\n up into two functions is so that once can call `encode_recent_observation`\n in between.\n\n Paramters\n ---------\n idx: int\n Index in buffer of recently observed frame (returned by `store_frame`).\n action: int\n Action that was performed upon observing this frame.\n reward: float\n Reward that was received when the actions was performed.\n done: bool\n True if episode was finished after performing that action.\n \"\"\"\n self.action[idx] = action\n self.reward[idx] = reward\n self.done[idx] = done\n\n" ]
[ [ "numpy.concatenate", "tensorflow.abs", "numpy.array", "numpy.zeros_like", "numpy.empty", "tensorflow.clip_by_norm", "tensorflow.variables_initializer", "tensorflow.train.ExponentialMovingAverage", "tensorflow.square" ] ]
supercaoO/WSR
[ "6087b5c70aa770020105553983586a2b4a0f4d40" ]
[ "networks/wsr_arch.py" ]
[ "import numpy as np\nfrom networks.block import *\nfrom pytorch_wavelets import DWTInverse\n\n\nclass RecurrentBlock(nn.Module):\n def __init__(self, num_features, num_simdb, act_type, norm_type):\n super(RecurrentBlock, self).__init__()\n self.compress_in = ConvBlock(2 * num_features, num_features, kernel_size=1, act_type=act_type,\n norm_type=norm_type)\n self.SIMDBs = []\n for _ in range(num_simdb):\n self.SIMDBs.append(SIMDB(in_channels=num_features))\n self.SIMDBs = nn.Sequential(*self.SIMDBs)\n\n self.should_reset = True\n self.last_hidden = None\n\n def forward(self, x):\n if self.should_reset:\n self.last_hidden = torch.zeros(x.size()).to(x.device)\n self.last_hidden.copy_(x)\n self.should_reset = False\n\n x = torch.cat((x, self.last_hidden), dim=1)\n x = self.compress_in(x)\n out = self.SIMDBs(x)\n self.last_hidden = out\n return out\n\n def reset_state(self):\n self.should_reset = True\n\n\nclass WSR(nn.Module):\n def __init__(self, in_channels, out_channels, num_features, num_simdb, upscale_factor, act_type='prelu',\n norm_type=None):\n super(WSR, self).__init__()\n\n padding = 2\n self.num_features = num_features\n self.upscale_factor = upscale_factor\n self.num_steps = int(np.log2(self.upscale_factor) + 1)\n\n # LR feature extraction block\n self.conv_in = ConvBlock(in_channels, 4 * num_features,\n kernel_size=3,\n act_type=act_type, norm_type=norm_type)\n self.feat_in = ConvBlock(4 * num_features, num_features,\n kernel_size=1,\n act_type=act_type, norm_type=norm_type)\n\n # recurrent block\n self.rb = RecurrentBlock(num_features, num_simdb, act_type, norm_type)\n\n # reconstruction block\n self.conv_steps = nn.ModuleList([\n nn.Sequential(ConvBlock(num_features, num_features, kernel_size=3, act_type=act_type, norm_type=norm_type),\n ConvBlock(num_features, out_channels, kernel_size=3, act_type=None, norm_type=norm_type)),\n\n nn.Sequential(ConvBlock(num_features, num_features, kernel_size=3, act_type=act_type, norm_type=norm_type),\n ConvBlock(num_features, out_channels * 3, kernel_size=3, act_type=None, norm_type=norm_type))]\n )\n for step in range(2, self.num_steps):\n conv_step = nn.Sequential(\n DeconvBlock(num_features, num_features, kernel_size=int(2 ** (step - 1) + 4),\n stride=int(2 ** (step - 1)), padding=padding, act_type=act_type, norm_type=norm_type),\n ConvBlock(num_features, out_channels * 3, kernel_size=3, act_type=None, norm_type=norm_type))\n self.conv_steps.append(conv_step)\n\n # inverse wavelet transformation\n self.ifm = DWTInverse(wave='db1', mode='symmetric').eval()\n for k, v in self.ifm.named_parameters():\n v.requires_grad = False\n\n def forward(self, x):\n self._reset_state()\n\n x = self.conv_in(x)\n x = self.feat_in(x)\n\n Yl = self.conv_steps[0](x)\n\n Yh = []\n for step in range(1, self.num_steps):\n h = self.rb(x)\n h = self.conv_steps[step](h)\n h = h.view(h.size()[0], h.size()[1] // 3, 3, h.size()[2], h.size()[3])\n Yh = [h] + Yh\n\n sr = self.ifm((Yl, Yh))\n\n return [Yl, Yh, sr]\n\n def _reset_state(self):\n self.rb.reset_state()\n" ]
[ [ "numpy.log2" ] ]
c-randall/p2d_pemfc
[ "3d8899b9ba4f7940b46851ab9c3f3ea79aaec736" ]
[ "pemfc_runner.py" ]
[ "\"\"\" Model Description \"\"\"\n\"-----------------------------------------------------------------------------\"\n\"\"\"This model is a half cell model of of PEM fuel cell cathode. The runner file\nallows the user to execute two different geometries for the catalyst layer:\ncore-shell and flodded-agglomerate. In the core-shell model, a Pt-covered \ncarbon core is covered with a thin shell of Nafion. In the flooded-agglomerate,\nmultiple core-shell geometries are clustered together and wrapped in an another\nshell of Nafion.\"\"\"\n\n\"\"\" Model Assumptions \"\"\"\n\"-----------------------------------------------------------------------------\"\n\" 1.) Gas properties are constant -> parameter\"\n\" 2.) Surface sites are constant -> parameter\"\n\" 3.) Temperature is constant -> parameter\"\n\" 4.) Variables are Phi_dl [V] -> only difference important, temp [K],\"\n\" Nafion/gas species mass densities, rho_naf_k and rho_gas_k [kg/m^3]\"\n\" 5.) The proton density in Nafion is constant due to its structure\"\n\" 6.) The C/Pt phase at every node has the same potential\"\n\" 7.) The ionic conductivity of Nafion is a function of its RH, temperature,\"\n\" and thickness and can be modeled via various sub models described in\"\n\" detail in the pemfc_property_func file.\"\n\n# Note: Interpolations can only be done within the ranges given by the above\n# mentioned paper [1]; therefore, this model only works for properties of \n# Nafion RH, temperature, and thickness of 20-95 %, 30-60 C, and 4-300 nm\n# respectively. Values outside of these ranges with result in an unknown\n# value of ionic conductivity.\n\n# Note: Another valuable paper for model inputs is \"An improved two-dimensional \n# agglomerate cathode model to study the influence of catalyst layer \n# structural parameters\" by Sun, Peppley, and Karan from 2005 [2]. This\n# includes GDL and CL thickness, porosities, and more.\n\n# Note: Permeability values taken as scaled values from Zenyuk, Das, Weber \n# paper that reported saturated values for GDL and CL at reported\n# porosities. Title \"Understanding Impacts of Catalyst Layer Thickness\n# on Fuel Cell Performance via Mathematical Modeling\" (2016) [3]. \n\n# Note: Oxygen diffusion through Nafion was taken from Sethuraman et al. paper \n# and scaled by water volume fraction as a function of t_naf. Titled \n# \"Measuring Oxygen, Carbon Monoxide, Hydrogen Sulfide Diffusion \n# Coefficients and Solubility in Nafion Membranes\" (2009) [4].\n\n# Note: Knowledge of O2 diffusion scaling with water volume fraction used to\n# scale values. Interpolations from DeCaluwe et al. taken to evaluate\n# water fraction as function of t_naf. Titled \"Structure-property \n# relationships at Nafion thin-film interfaces:...\" (2018) [5]\n\n# Note: Nafion conducitivity treatment as bulk material was added as an option.\n# This method assumes the thin shell has the same conductivity as bulk\n# material and that there are no confinement or microstructure effects\n# when it gets too thin. The relationship is taken from Yadav et al. in\n# their 2012 publication of \"Analysis of EIS Technique and Nafion 117 \n# Conductivity as a Function of Temperature and Relative Humidity\" [6]\n\n# Note: Low Pt loading data and modeling results are present with operating \n# conditions in \"Modeling and Experimental Validation of Pt Loading and\n# Electrode Composition Efects in PEM Fuel Cells\" by L. Hao et. al. [7]\n# This paper was published in 2015 and makes it recent enough to validate\n# against.\n\n# Note: In order to validate the model, results for the full cell are needed.\n# The anode was added by determining the steady-state potential via\n# Gibb's free energy correlations. The PEM was simply modeled as a V=IR\n# relationship where the resistance (Ohm*cm^2) was taken from [8] (2002).\n\n\"\"\" Import needed modules \"\"\"\n\"-----------------------------------------------------------------------------\"\nimport numpy as np\nimport cantera as ct\n\n\"\"\" User Input Parameters \"\"\"\n\"-----------------------------------------------------------------------------\"\nmodel = 'core_shell' # CL geom: 'core_shell' or 'flooded_agg'\nrxn_mech = '2s' # '1s' or '2s' for 1- or 2-step reaction\n\n\" Initial electrochemical values \"\ni_OCV = 0 # 0 [A/cm^2] -> or single run if != 0 \ni_ext0 = np.array([0.05, 0.20, 0.40, 0.80, 1.0, 1.2, 1.5, 1.65, 1.85, 2.0])\ni_ext1 = np.array([])\ni_ext2 = np.array([])\n\n#i_ext0 = np.linspace(0.001,0.1,5) # external currents close to 0 [A/cm^2]\n#i_ext1 = np.linspace(0.101,1.0,5) # external currents [A/cm^2]\n#i_ext2 = np.linspace(1.100,2.0,5) # external currents further from 0 [A/cm^2]\n\nphi_ca_init = 0.7 # initial cathode potential [V]\nT_ca, P_ca = 333, 1.5*ct.one_atm # cathode temp [K] and pressure [Pa] at t = 0\nT_an, P_an = 333, 1.5*ct.one_atm # anode temp [K] and pressure [Pa] at t = 0\n\n\" Transport and material properties \"\nRH = 95 # relative humidity of Nafion phase [%]\nC_dl = 1.5e-9 # capacitance of double layer [F/m^2]\nsig_method = 'mix' # 'lam', 'bulk', 'mix', or 'sun' for conductivity method\nD_O2_method = 'mix' # 'lam', 'bulk', 'mix', or 'sun' for D_O2 method\nR_naf = 45e-3 # resistance of Nafion membrane [Ohm*cm^2]\n\n\" Pt loading and geometric values \"\narea_calcs = 1 # control for area calculations [0:p_Pt, 1:Pt_loading]\np_Pt = 10 # percentage of Pt covering the carbon particle surface [%]\nw_Pt = 0.2 # loading of Pt on carbon [mg/cm^2]\nrho_Pt = 21.45e3 # density of Pt for use in area property calcs [kg/m^3]\nr_c = 50e-9 # radius of single carbon particle [m] (50:cs, 25:fa)\nr_Pt = 1e-9 # radius of Pt 1/2 sphere sitting on C surface [m]\nt_gdl = 250e-6 # thickness of cathode GDL modeled in simulation [m]\nt_cl = 15e-6 # thickness of cathode CL modeled in simulation [m]\nt_naf = 5e-9 # thickness of nafion around each core/agglomerate [m]\neps_g_gdl = 0.5 # porosity of GDL [-]\neps_g_cl = 0.1 # porosity of CL [-]\n\n\" Core-shell specific geometry values \"\ntheta = 45 # O2 transport angle (<90) for Nafion SA [degrees]\n\n\" Flooded-agglomerate specific geometry values \"\np_c = 95 # % of C sheres packed in agglomerate - Gauss max = 74%\nr_agg = 50e-9 # radius of agglomerate excluding nafion shell [m]\n\n\" Gas channel boundary conditions \"\nY_ca_BC = 'N2: 0.79, O2: 0.21, Ar: 0.01, H2O: 0.03, OH: 0'\nT_ca_BC, P_ca_BC = 333, 1.5*ct.one_atm # cathode gas channel T [K] and P [Pa]\n\n\" Reaction properties \"\nn_elec_an = 2 # sum(nu_k*z_k) for anode surface reaction from ctifile\n\n\" Model inputs \"\nind_e = 0 # index of electrons in Pt surface phase... from cti\nmethod = 'BDF' # method for solve_ivp [eg: BDF,RK45,LSODA,Radau,etc...]\nt_sim = 1e2 # time span of integration [s]\nNy_gdl = 3 # number of depth discretizations for GDL\nNy_cl = 3 # number of depth discretizations for CL\nNr_cl = 3 # number of radial discretizations for CL nafion shells\n\n\" Modify tolerance for convergence \"\nmax_t = t_sim # maximum allowable time step for solver [s]\natol = 1e-9 # absolute tolerance passed to solver\nrtol = 1e-6 # relative tolerance passed to solver\n\n\" Plot toggles - (0: off and 1: on) \"\npost_only = 0 # turn on to only run post-processing\ndebug = 0 # turn on to plot solution vector variables vs time\nradial = 0 # turn on radial O2 plots for each Nafion shell/agglomerate\ngrads = 0 # turn on to plot O2, Phi, and i_far gradients vs CL depth\npolar = 1 # turn on to generate full cell polarization curves\nover_p = 0 # turn on to plot overpotential curve for cathode\n\n\" Verification settings \"\ndata = 1 # include data from Owejan et. al. if available (0: off, 1: on)\ni_ver = 1 # verify current between GDL and CL (0: off, 1: on)\ni_find = 0.5 # current from polarization to use in i_ver calculation [A/cm^2]\n\n\" Plotting options \"\nfont_nm = 'Arial' # name of font for plots\nfont_sz = 14 # size of font for plots\n\n\" Saving options \"\nfolder_name = 'folder_name' # folder name for saving all files/outputs\nsave = 0 # toggle saving on/off with '1' or '0'\n\n\"\"\" End of user inputs - do not edit anything below this line \"\"\"\n\"-----------------------------------------------------------------------------\"\n###############################################################################\n###############################################################################\n###############################################################################\n\nif model == 'core_shell': \n ctifile, ver, R_naf, r_c = 'pemfc_cs.cti', 1, 0e-3, 50e-9\n sig_method, D_O2_method = 'mix', 'mix'\nelif model == 'flooded_agg': \n ctifile, ver, R_naf, r_c = 'pemfc_fa.cti', 2, 60e-3, 25e-9\n sig_method, D_O2_method = 'sun', 'sun'\n\n\"\"\" Process inputs from this file and run model \"\"\"\n\"-----------------------------------------------------------------------------\"\nif __name__ == '__main__': \n if post_only == 0:\n exec(open(\"Shared_Funcs/pemfc_pre.py\").read())\n exec(open(\"Shared_Funcs/pemfc_dsvdt.py\").read())\n \n exec(open(\"Shared_Funcs/pemfc_post.py\").read())\n" ]
[ [ "numpy.array" ] ]
Nit-1997/AntiPhishing
[ "4e6ddc742d1d786b822d41c80c7378b5b51d5b67" ]
[ "boards/AntiPhishing.py" ]
[ "# -*- coding: utf-8 -*-\r\n\r\n\r\nimport pandas as pd\r\nfrom sklearn.utils import shuffle\r\nimport ipaddress\r\nfrom os.path import splitext\r\nfrom urllib.parse import urlparse\r\nimport tldextract\r\n\r\ndef filetoDF(file):\r\n file = \"dataset2.csv\"\r\n df = pd.read_csv(file)\r\n print(df.head())\r\n return df\r\n\r\ndef countDots(url):\r\n return url.count('.')\r\n\r\ndef countDelimiter(url):\r\n delim = ['&','?','=',';','_']\r\n count = 0\r\n for ch in url:\r\n if ch in delim:\r\n count += 1\r\n return count\r\n\r\ndef hyphenCount(url):\r\n return url.count('-')\r\n\r\ndef isIPaddress(domain):\r\n try:\r\n if ipaddress.ip_address(domain):\r\n return 1\r\n except:\r\n return 0\r\ndef atCount(url):\r\n return url.count('@')\r\n\r\ndef doubleSlashCount(url):\r\n return url.count('//')\r\n\r\ndef subDirCount(url):\r\n return url.count('/')\r\n\r\ndef fileExt(url):\r\n rest,extension = splitext(url)\r\n return extension\r\n\r\ndef subDomainCount(subdomain):\r\n if not subdomain:\r\n return 0\r\n else:\r\n return len(subdomain.split('.'))\r\n\r\ndef queryCount(query):\r\n if not query:\r\n return 0\r\n return len(query.split('&'))\r\n\r\ndef suspiciousTLD(suffix):\r\n TLD = ['zip','cricket','link','work','party','gq','kim','country','science','tk']\r\n if suffix in TLD:\r\n return 1\r\n return 0\r\n\r\ndef extractFeatures(url,label):\r\n row = []\r\n print(url)\r\n parse = urlparse(url)\r\n extract = tldextract.extract(url)\r\n url = str(url)\r\n row.append(url)\r\n\r\n row.append(countDots(extract.subdomain))\r\n row.append(hyphenCount(parse.netloc))\r\n row.append(len(url))\r\n row.append(atCount(parse.netloc))\r\n row.append(doubleSlashCount(parse.path))\r\n row.append(subDirCount(parse.path))\r\n row.append(subDomainCount(extract.subdomain))\r\n row.append(len(parse.netloc))\r\n row.append(queryCount(parse.query))\r\n row.append(isIPaddress(extract.domain))\r\n row.append(suspiciousTLD(extract.suffix))\r\n row.append(label)\r\n return row\r\n\r\ndef makeDataset(file):\r\n featureSet = pd.DataFrame(columns=('url','no of dots','no of hyphen','len of url','presence of @',\\\r\n 'presence of //','no of subdir','no of subdomain','len of domain','no of queries','is IP','Suspicious_TLD',\\\r\n 'label'))\r\n df = filetoDF(file)\r\n for i in range(len(df)):\r\n features = extractFeatures(df[\"URL\"].loc[i],df[\"Label\"].loc[i])\r\n featureSet.loc[i] = features\r\n\r\n\r\n#makeDataset(df)\r\n" ]
[ [ "pandas.DataFrame", "pandas.read_csv" ] ]
huan123/py-fatser-rcnn
[ "b0c02e004bcd480a01671603578fe18740b85ac0" ]
[ "tools/trainval_net.py" ]
[ "# -*- coding: utf-8 -*-\n# --------------------------------------------------------\n# Tensorflow Faster R-CNN\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Zheqi He, Xinlei Chen, based on code from Ross Girshick\n# --------------------------------------------------------\n#使用voc训练时配置参数\n# --weight\n# data/imagenet_weights/vgg16.ckpt\n# --imdb\n# voc_2007_trainval\n# --imdbval\n# voc_2007_test\n# --iters\n# 110000\n# --cfg\n# experiments/cfgs/vgg16.yml\n# --net\n# vgg16\n# --set\n# ANCHOR_SCALES\n# [8,16,32]\n\n#使用coco\n# --weight\n# data/imagenet_weights/vgg16.ckpt\n# --imdb\n# coco_2014_train+coco_2014_valminusminival\n# --imdbval\n# coco_2014_minival\n# --iters\n# 490000\n# --cfg\n# experiments/cfgs/vgg16.yml\n# --net\n# vgg16\n# --set\n# ANCHOR_SCALES\n# [4,8,16,32]\n\n#自己的\n# --weight\n# data/imagenet_weights/vgg16.ckpt\n# --imdb\n# coco_2014_train+coco_2014_valminusminival\n# --imdbval\n# coco_2014_minival\n# --iters\n# 490\n# --cfg\n# experiments/cfgs/vgg16.yml\n# --net\n# vgg16\n# --set\n# ANCHOR_SCALES\n# [4,8,16,32]\n#\n\n\n#train_net.py:使用fast rcnn,训练自己数据集的网络模型\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\n#sys.path.insert(0, '/Users/huan/code/PycharmProjects/tf-faster-rcnn/lib')\nimport tools._init_paths\nfrom model.train_val import get_training_roidb, train_net\nfrom model.config import cfg, cfg_from_file, cfg_from_list, get_output_dir, get_output_tb_dir\nfrom datasets.factory import get_imdb\nimport datasets.imdb\nimport argparse\nimport pprint\nimport numpy as np\nimport sys\nimport argparse\nimport tensorflow as tf\nfrom nets.vgg16 import vgg16\nfrom nets.resnet_v1 import resnetv1\nfrom nets.mobilenet_v1 import mobilenetv1\n\ndef parse_args():\n \"\"\"\n Parse input arguments\n \"\"\"\n parser = argparse.ArgumentParser(description='Train a Fast R-CNN network')\n parser.add_argument('--cfg', dest='cfg_file',\n help='optional config file',\n default=None, type=str)\n parser.add_argument('--weight', dest='weight',\n help='initialize with pretrained model weights',\n type=str)\n parser.add_argument('--imdb', dest='imdb_name',\n help='dataset to train on',\n default='voc_2007_trainval', type=str)\n parser.add_argument('--imdbval', dest='imdbval_name',\n help='dataset to validate on',\n default='voc_2007_test', type=str)\n parser.add_argument('--iters', dest='max_iters',\n help='number of iterations to train',\n default=70000, type=int)\n parser.add_argument('--tag', dest='tag',\n help='tag of the model',\n default=None, type=str)\n parser.add_argument('--net', dest='net',\n help='vgg16, res50, res101, res152, mobile',\n default='res50', type=str)\n parser.add_argument('--set', dest='set_cfgs',\n help='set config keys', default=None,\n nargs=argparse.REMAINDER)\n\n if len(sys.argv) == 1:\n parser.print_help()\n sys.exit(1)\n\n args = parser.parse_args()\n return args\n\n\ndef combined_roidb(imdb_names):\n \"\"\"\n Combine multiple roidbs\n \"\"\"\n #roidb是一个列表,列表的长度是读取的图片文件个数的两倍(注意,经过了图片翻转),列表中的每一个元素都是一个字典,\n #而且字典的key包括:'boxes' 、'gt_classes'、'gt_overlaps'、'flipped'(原始图片取值为:False,翻转之后的图片取值为:True)、'image'、'width'、'height'、'max_classes'、'max_overlaps'。\n def get_roidb(imdb_name):\n imdb = get_imdb(imdb_name)\n print('Loaded dataset `{:s}` for training'.format(imdb.name))\n imdb.set_proposal_method(cfg.TRAIN.PROPOSAL_METHOD)\n print('Set proposal method: {:s}'.format(cfg.TRAIN.PROPOSAL_METHOD))\n roidb = get_training_roidb(imdb)\n return roidb\n\n roidbs = [get_roidb(s) for s in imdb_names.split('+')]\n roidb = roidbs[0]\n if len(roidbs) > 1:\n for r in roidbs[1:]:\n roidb.extend(r)\n tmp = get_imdb(imdb_names.split('+')[1])\n imdb = datasets.imdb.imdb(imdb_names, tmp.classes)\n else:\n imdb = get_imdb(imdb_names)\n return imdb, roidb\n\n\nif __name__ == '__main__':\n args = parse_args()\n\n print('Called with args:')\n print(args)\n\n if args.cfg_file is not None:\n cfg_from_file(args.cfg_file)\n if args.set_cfgs is not None:\n cfg_from_list(args.set_cfgs)\n\n print('Using config:')\n #print.pprint(cfg)\n print(cfg)\n\n np.random.seed(cfg.RNG_SEED)\n\n # train set\n imdb, roidb = combined_roidb(args.imdb_name)\n print('{:d} roidb entries'.format(len(roidb)))\n\n #todo 为了生成pkl,先将除了训练以外的注释掉\n # output directory where the models are saved\n output_dir = get_output_dir(imdb, args.tag)\n print('Output will be saved to `{:s}`'.format(output_dir))\n\n # tensorboard directory where the summaries are saved during training\n tb_dir = get_output_tb_dir(imdb, args.tag)\n print('TensorFlow summaries will be saved to `{:s}`'.format(tb_dir))\n\n # also add the validation set, but with no flipping images\n orgflip = cfg.TRAIN.USE_FLIPPED\n cfg.TRAIN.USE_FLIPPED = False\n #todo 测试被注释\n\n _, valroidb = combined_roidb(args.imdbval_name)\n print('{:d} validation roidb entries'.format(len(valroidb)))\n cfg.TRAIN.USE_FLIPPED = orgflip\n\n # load network\n if args.net == 'vgg16':\n net = vgg16()\n elif args.net == 'res50':\n net = resnetv1(num_layers=50)\n elif args.net == 'res101':\n net = resnetv1(num_layers=101)\n elif args.net == 'res152':\n net = resnetv1(num_layers=152)\n elif args.net == 'mobile':\n net = mobilenetv1()\n else:\n raise NotImplementedError\n\n train_net(net, imdb, roidb, valroidb, output_dir, tb_dir,\n pretrained_model=args.weight,\n max_iters=args.max_iters)\n" ]
[ [ "numpy.random.seed" ] ]
li-phone/DefectNet
[ "f1b6f44a34581c8942d7ee5341cb9da4e76a225a" ]
[ "mmdet/models/detectors/two_stage.py" ]
[ "import torch\nimport torch.nn as nn\n\nfrom mmcv.utils.config import Dict\nfrom mmdet.core import bbox2result, bbox2roi, build_assigner, build_sampler\nfrom .. import builder\nfrom ..registry import DETECTORS\nfrom .base import BaseDetector\nfrom .test_mixins import BBoxTestMixin, MaskTestMixin, RPNTestMixin\n\n\[email protected]_module\nclass TwoStageDetector(BaseDetector, RPNTestMixin, BBoxTestMixin,\n MaskTestMixin):\n \"\"\"Base class for two-stage detectors.\n\n Two-stage detectors typically consisting of a region proposal network and a\n task-specific regression head.\n \"\"\"\n\n def __init__(self,\n backbone,\n dfn_balance=None,\n ignore_ids=None,\n neck=None,\n shared_head=None,\n rpn_head=None,\n bbox_roi_extractor=None,\n bbox_head=None,\n mask_roi_extractor=None,\n mask_head=None,\n train_cfg=None,\n test_cfg=None,\n pretrained=None):\n super(TwoStageDetector, self).__init__()\n self.backbone = builder.build_backbone(backbone)\n\n if dfn_balance is None:\n self.dfn_balance = dfn_balance\n else:\n self.dfn_balance = Dict(dfn_balance)\n self.ignore_ids = ignore_ids\n\n if neck is not None:\n self.neck = builder.build_neck(neck)\n\n if shared_head is not None:\n self.shared_head = builder.build_shared_head(shared_head)\n\n if rpn_head is not None:\n self.rpn_head = builder.build_head(rpn_head)\n\n if bbox_head is not None:\n self.bbox_roi_extractor = builder.build_roi_extractor(\n bbox_roi_extractor)\n self.bbox_head = builder.build_head(bbox_head)\n\n if mask_head is not None:\n if mask_roi_extractor is not None:\n self.mask_roi_extractor = builder.build_roi_extractor(\n mask_roi_extractor)\n self.share_roi_extractor = False\n else:\n self.share_roi_extractor = True\n self.mask_roi_extractor = self.bbox_roi_extractor\n self.mask_head = builder.build_head(mask_head)\n\n self.train_cfg = train_cfg\n self.test_cfg = test_cfg\n\n self.init_weights(pretrained=pretrained)\n\n @property\n def with_rpn(self):\n return hasattr(self, 'rpn_head') and self.rpn_head is not None\n\n def init_weights(self, pretrained=None):\n super(TwoStageDetector, self).init_weights(pretrained)\n self.backbone.init_weights(pretrained=pretrained)\n if self.with_neck:\n if isinstance(self.neck, nn.Sequential):\n for m in self.neck:\n m.init_weights()\n else:\n self.neck.init_weights()\n if self.with_shared_head:\n self.shared_head.init_weights(pretrained=pretrained)\n if self.with_rpn:\n self.rpn_head.init_weights()\n if self.with_bbox:\n self.bbox_roi_extractor.init_weights()\n self.bbox_head.init_weights()\n if self.with_mask:\n self.mask_head.init_weights()\n if not self.share_roi_extractor:\n self.mask_roi_extractor.init_weights()\n\n def extract_feat(self, img):\n \"\"\"Directly extract features from the backbone+neck\n \"\"\"\n x = self.backbone(img)\n if self.with_neck:\n x = self.neck(x)\n return x\n\n def extract_defect_feat(self, img, targets=None):\n if targets is None:\n x1, x2 = self.backbone(img, detector=True)\n score = x2.softmax(dim=1)\n label = int(score.argmax(dim=1))\n if label == 0:\n return x1, label\n if self.with_neck:\n x1 = self.neck(x1)\n return x1, label\n else:\n x1, x2 = self.backbone(img, detector=True, targets=targets)\n if self.with_neck:\n x1 = self.neck(x1)\n return x1, x2\n\n def forward_dummy(self, img):\n \"\"\"Used for computing network flops.\n\n See `mmedetection/tools/get_flops.py`\n \"\"\"\n outs = ()\n # backbone\n x = self.extract_feat(img)\n # rpn\n if self.with_rpn:\n rpn_outs = self.rpn_head(x)\n outs = outs + (rpn_outs,)\n proposals = torch.randn(1000, 4).cuda()\n # bbox head\n rois = bbox2roi([proposals])\n if self.with_bbox:\n bbox_feats = self.bbox_roi_extractor(\n x[:self.bbox_roi_extractor.num_inputs], rois)\n if self.with_shared_head:\n bbox_feats = self.shared_head(bbox_feats)\n cls_score, bbox_pred = self.bbox_head(bbox_feats)\n outs = outs + (cls_score, bbox_pred)\n # mask head\n if self.with_mask:\n mask_rois = rois[:100]\n mask_feats = self.mask_roi_extractor(\n x[:self.mask_roi_extractor.num_inputs], mask_rois)\n if self.with_shared_head:\n mask_feats = self.shared_head(mask_feats)\n mask_pred = self.mask_head(mask_feats)\n outs = outs + (mask_pred,)\n return outs\n\n def get_dfn_weight(self, n=None):\n k = self.dfn_balance.scale_factor\n w0 = self.dfn_balance.init_weight\n T = self.dfn_balance.period\n if self.dfn_balance.type == 'constant':\n return w0\n elif self.dfn_balance.type == 'linear':\n return -k * (n / T) + w0\n elif self.dfn_balance.type == 'inverse':\n return k * w0 / ((n / T) + 1)\n elif self.dfn_balance.type == 'exponent':\n a = self.dfn_balance.base\n return k * w0 / (max(a ** (n / T), 1e-6))\n else:\n raise Exception('No {} implement'.format(str(self.dfn_balance.type)))\n\n def forward_train(self,\n img,\n img_meta,\n gt_bboxes,\n gt_labels,\n gt_bboxes_ignore=None,\n gt_masks=None,\n proposals=None,\n epoch=None,\n **kwargs):\n \"\"\"\n Args:\n img (Tensor): of shape (N, C, H, W) encoding input images.\n Typically these should be mean centered and std scaled.\n\n img_meta (list[dict]): list of image info dict where each dict has:\n 'img_shape', 'scale_factor', 'flip', and may also contain\n 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'.\n For details on the values of these keys see\n `mmdet/datasets/pipelines/formatting.py:Collect`.\n\n gt_bboxes (list[Tensor]): each item are the truth boxes for each\n image in [tl_x, tl_y, br_x, br_y] format.\n\n gt_labels (list[Tensor]): class indices corresponding to each box\n\n gt_bboxes_ignore (None | list[Tensor]): specify which bounding\n boxes can be ignored when computing the loss.\n\n gt_masks (None | Tensor) : true segmentation masks for each box\n used if the architecture supports a segmentation task.\n\n proposals : override rpn proposals with custom proposals. Use when\n `with_rpn` is False.\n\n Returns:\n dict[str, Tensor]: a dictionary of loss components\n \"\"\"\n # x = self.extract_feat(img)\n\n losses = dict()\n\n # keep the original usage\n if self.dfn_balance is None:\n x = self.extract_feat(img)\n else:\n # count the number of defects in each image\n defect_nums = [0] * img.shape[0]\n for i, gt_label in enumerate(gt_labels):\n defect_cnt = 0\n for label in gt_label:\n if self.dfn_balance.background_id != int(label):\n defect_cnt += 1\n defect_nums[i] = defect_cnt\n\n # split the images into defect(1) image and normal(0) image\n dfn_labels = [0 if i == 0 else 1 for i in defect_nums]\n dfn_labels = torch.Tensor(dfn_labels).long().cuda()\n\n # calculate dfn loss\n x, dfn_loss = self.extract_defect_feat(img, targets=dfn_labels)\n\n # balance different network loss\n dfn_weight = self.get_dfn_weight(epoch)\n loss_dfn = dfn_loss['loss']\n loss_dfn = loss_dfn * dfn_weight\n losses.update(loss_dfn=loss_dfn)\n\n # delete the ignored annotations\n if self.ignore_ids is not None:\n for ignore_id in self.ignore_ids:\n for i, gt_label in enumerate(gt_labels):\n keep_ind = gt_label != ignore_id\n gt_labels[i] = gt_labels[i][keep_ind]\n gt_bboxes[i] = gt_bboxes[i][keep_ind]\n keep_ind = [True] * len(gt_labels)\n for i in range(len(gt_labels) - 1, -1, -1):\n if gt_labels[i].shape[0] == 0:\n img_meta.pop(i)\n gt_bboxes.pop(i)\n gt_labels.pop(i)\n keep_ind[i] = False\n img = img[keep_ind]\n x = list(x)\n for i in range(len(x)):\n x[i] = x[i][keep_ind]\n x = tuple(x)\n\n # if have no any images, then set all loss to be 0 except dfn loss\n if len(gt_labels) == 0 or len(gt_bboxes) == 0 or img.shape[0] == 0:\n loss_zeros = [torch.Tensor([0.]).float().cuda() for i in range(len(x))]\n loss_ones = [torch.Tensor([1.]).float().cuda() for i in range(len(x))]\n losses.update(loss_rpn_cls=loss_zeros, loss_rpn_bbox=loss_zeros)\n loss_zero = torch.Tensor([0.]).float().cuda()\n loss_one = torch.Tensor([1.]).float().cuda()\n losses['loss_cls'] = loss_zero\n losses['loss_bbox'] = loss_zero\n losses['acc'] = loss_one\n return losses\n\n # RPN forward and loss\n if self.with_rpn:\n rpn_outs = self.rpn_head(x)\n rpn_loss_inputs = rpn_outs + (gt_bboxes, img_meta,\n self.train_cfg.rpn)\n rpn_losses = self.rpn_head.loss(\n *rpn_loss_inputs, gt_bboxes_ignore=gt_bboxes_ignore)\n losses.update(rpn_losses)\n\n proposal_cfg = self.train_cfg.get('rpn_proposal',\n self.test_cfg.rpn)\n proposal_inputs = rpn_outs + (img_meta, proposal_cfg)\n proposal_list = self.rpn_head.get_bboxes(*proposal_inputs)\n else:\n proposal_list = proposals\n\n # assign gts and sample proposals\n if self.with_bbox or self.with_mask:\n bbox_assigner = build_assigner(self.train_cfg.rcnn.assigner)\n bbox_sampler = build_sampler(\n self.train_cfg.rcnn.sampler, context=self)\n num_imgs = img.size(0)\n if gt_bboxes_ignore is None:\n gt_bboxes_ignore = [None for _ in range(num_imgs)]\n sampling_results = []\n for i in range(num_imgs):\n assign_result = bbox_assigner.assign(proposal_list[i],\n gt_bboxes[i],\n gt_bboxes_ignore[i],\n gt_labels[i])\n sampling_result = bbox_sampler.sample(\n assign_result,\n proposal_list[i],\n gt_bboxes[i],\n gt_labels[i],\n feats=[lvl_feat[i][None] for lvl_feat in x])\n sampling_results.append(sampling_result)\n\n # bbox head forward and loss\n if self.with_bbox:\n rois = bbox2roi([res.bboxes for res in sampling_results])\n # TODO: a more flexible way to decide which feature maps to use\n bbox_feats = self.bbox_roi_extractor(\n x[:self.bbox_roi_extractor.num_inputs], rois)\n if self.with_shared_head:\n bbox_feats = self.shared_head(bbox_feats)\n cls_score, bbox_pred = self.bbox_head(bbox_feats)\n\n bbox_targets = self.bbox_head.get_target(sampling_results,\n gt_bboxes, gt_labels,\n self.train_cfg.rcnn)\n loss_bbox = self.bbox_head.loss(cls_score, bbox_pred,\n *bbox_targets)\n losses.update(loss_bbox)\n\n # mask head forward and loss\n if self.with_mask:\n if not self.share_roi_extractor:\n pos_rois = bbox2roi(\n [res.pos_bboxes for res in sampling_results])\n mask_feats = self.mask_roi_extractor(\n x[:self.mask_roi_extractor.num_inputs], pos_rois)\n if self.with_shared_head:\n mask_feats = self.shared_head(mask_feats)\n else:\n pos_inds = []\n device = bbox_feats.device\n for res in sampling_results:\n pos_inds.append(\n torch.ones(\n res.pos_bboxes.shape[0],\n device=device,\n dtype=torch.uint8))\n pos_inds.append(\n torch.zeros(\n res.neg_bboxes.shape[0],\n device=device,\n dtype=torch.uint8))\n pos_inds = torch.cat(pos_inds)\n mask_feats = bbox_feats[pos_inds]\n\n if mask_feats.shape[0] > 0:\n mask_pred = self.mask_head(mask_feats)\n mask_targets = self.mask_head.get_target(\n sampling_results, gt_masks, self.train_cfg.rcnn)\n pos_labels = torch.cat(\n [res.pos_gt_labels for res in sampling_results])\n loss_mask = self.mask_head.loss(mask_pred, mask_targets,\n pos_labels)\n losses.update(loss_mask)\n\n return losses\n\n async def async_simple_test(self,\n img,\n img_meta,\n proposals=None,\n rescale=False,\n **kwargs):\n \"\"\"Async test without augmentation.\"\"\"\n assert self.with_bbox, \"Bbox head must be implemented.\"\n x = self.extract_feat(img)\n\n if proposals is None:\n proposal_list = await self.async_test_rpn(x, img_meta,\n self.test_cfg.rpn)\n else:\n proposal_list = proposals\n\n det_bboxes, det_labels = await self.async_test_bboxes(\n x, img_meta, proposal_list, self.test_cfg.rcnn, rescale=rescale)\n bbox_results = bbox2result(det_bboxes, det_labels,\n self.bbox_head.num_classes)\n\n if not self.with_mask:\n return bbox_results\n else:\n segm_results = await self.async_test_mask(\n x,\n img_meta,\n det_bboxes,\n det_labels,\n rescale=rescale,\n mask_test_cfg=self.test_cfg.get('mask'))\n return bbox_results, segm_results\n\n def simple_test(self, img, img_meta, proposals=None, rescale=False, **kwargs):\n \"\"\"Test without augmentation.\"\"\"\n assert self.with_bbox, \"Bbox head must be implemented.\"\n\n # x = self.extract_feat(img)\n\n if self.dfn_balance is None:\n x = self.extract_feat(img)\n elif self.dfn_balance.init_weight == 0:\n x, x2 = self.extract_defect_feat(img)\n if x2 == 0 and self.with_neck:\n x = self.neck(x)\n else:\n x, x2 = self.extract_defect_feat(img)\n if x2 == 0:\n return x2\n\n if proposals is None:\n proposal_list = self.simple_test_rpn(x, img_meta,\n self.test_cfg.rpn)\n else:\n proposal_list = proposals\n\n det_bboxes, det_labels = self.simple_test_bboxes(\n x, img_meta, proposal_list, self.test_cfg.rcnn, rescale=rescale)\n bbox_results = bbox2result(det_bboxes, det_labels,\n self.bbox_head.num_classes)\n\n if not self.with_mask:\n return bbox_results\n else:\n segm_results = self.simple_test_mask(\n x, img_meta, det_bboxes, det_labels, rescale=rescale)\n return bbox_results, segm_results\n\n def aug_test(self, imgs, img_metas, rescale=False):\n \"\"\"Test with augmentations.\n\n If rescale is False, then returned bboxes and masks will fit the scale\n of imgs[0].\n \"\"\"\n # recompute feats to save memory\n proposal_list = self.aug_test_rpn(\n self.extract_feats(imgs), img_metas, self.test_cfg.rpn)\n det_bboxes, det_labels = self.aug_test_bboxes(\n self.extract_feats(imgs), img_metas, proposal_list,\n self.test_cfg.rcnn)\n\n if rescale:\n _det_bboxes = det_bboxes\n else:\n _det_bboxes = det_bboxes.clone()\n _det_bboxes[:, :4] *= img_metas[0][0]['scale_factor']\n bbox_results = bbox2result(_det_bboxes, det_labels,\n self.bbox_head.num_classes)\n\n # det_bboxes always keep the original scale\n if self.with_mask:\n segm_results = self.aug_test_mask(\n self.extract_feats(imgs), img_metas, det_bboxes, det_labels)\n return bbox_results, segm_results\n else:\n return bbox_results\n" ]
[ [ "torch.zeros", "torch.cat", "torch.ones", "torch.Tensor", "torch.randn" ] ]
stanley-chang/I2DL
[ "78740460e1f52ce7643358fc548281f1bbe73a42" ]
[ "exercise_11/exercise_code/rnn/base_classifier.py" ]
[ "import pytorch_lightning as pl\nimport torch\nimport numpy as np\nimport torch.nn as nn\nimport pickle\nimport torch.nn.functional as F\nfrom torchvision import transforms\nfrom .mnist_dataset import *\n\nclass Base_Classifier(pl.LightningModule):\n\n def general_step(self, batch, batch_idx, mode):\n images, targets = batch\n\n # forward pass\n\n # out = self.forward(images)\n outputs = self.forward(images.squeeze(1).permute(1,0,2).float())\n \n # loss\n loss = F.cross_entropy(outputs, targets)\n\n # accuracy\n _, preds = torch.max(outputs, 1) # convert output probabilities to predicted class\n acc = torch.mean((preds == targets).float())\n\n return loss, acc\n\n\n def training_step(self, batch, batch_idx):\n loss, acc = self.general_step(batch, batch_idx, \"train\")\n tensorboard_logs = {'loss': loss, 'train_accuracy': acc}\n return {'loss': loss, 'train_acc':acc, 'log': tensorboard_logs}\n\n\n def validation_step(self, batch, batch_idx):\n loss, acc = self.general_step(batch, batch_idx, \"train\")\n return {'val_loss': loss, 'val_acc': acc}\n \n\n def test_step(self, batch, batch_idx):\n loss, acc = self.general_step(batch, batch_idx, \"test\")\n return {'test_loss': loss, 'test_acc': acc}\n\n\n def validation_epoch_end(self, outputs):\n avg_loss = torch.stack([x['val_loss'] for x in outputs]).mean()\n avg_acc = torch.stack([x['val_acc'] for x in outputs]).mean()\n print(\"valiadation accuracy at currect epoch is {}\".format(avg_acc))\n tensorboard_logs = {'val_loss': avg_loss, 'val_acc': avg_acc}\n\n return {'val_loss': avg_loss, 'log': tensorboard_logs}\n\n def prepare_data(self):\n \n transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.5,), std=(0.5,))\n ])\n\n with open(self.path, \"rb\") as f:\n mnist_raw = pickle.load(f)\n\n X, y= mnist_raw\n train_split=0.85\n\n self.train_dset=MnistDataset(X[:int(len(X)*train_split)], y[:int(len(X)*train_split)], transform=transform)\n self.val_dset=MnistDataset(X[int(len(X)*train_split):], y[int(len(X)*train_split):], transform=transform)\n\n\n @pl.data_loader\n def train_dataloader(self):\n batch_size = 128\n train_loader = torch.utils.data.DataLoader(\n dataset=self.train_dset,\n batch_size=batch_size,\n shuffle=True)\n \n return train_loader\n\n\n @pl.data_loader\n def val_dataloader(self):\n batch_size = 128\n val_loader = torch.utils.data.DataLoader(\n dataset=self.val_dset,\n batch_size=batch_size,\n shuffle=False)\n return val_loader\n\n def configure_optimizers(self):\n\n optim = torch.optim.Adam(self.parameters(), lr=1e-3, eps=1e-8, betas=(0.9, 0.999))\n return optim\n \n def set_data_path(self, path):\n self.path = path" ]
[ [ "torch.nn.functional.cross_entropy", "torch.stack", "torch.utils.data.DataLoader", "torch.max" ] ]
maxkrakauer/BERT
[ "cf05ef98e459bfd64e3dad0d423a0f9ccef5a4d9" ]
[ "AlephBERT-main/models/alephbert-base/hebrew-model.py" ]
[ "import json\nfrom transformers import BertForMaskedLM, BertTokenizerFast\nimport torch\nimport pickle\nimport io\nimport sys\n\ntorch.device('cpu')\n\n\nclass CPU_Unpickler(pickle.Unpickler):\n def find_class(self, module, name):\n if module == 'torch.storage' and name == '_load_from_bytes':\n return lambda b: torch.load(io.BytesIO(b), map_location='cpu')\n else:\n return super().find_class(module, name)\n\n\ntext = sys.argv[1]\nmask = sys.argv[2]\noriginal = sys.argv[3]\n\nalephbert_tokenizer = BertTokenizerFast.from_pretrained(\n 'onlplab/alephbert-base')\n\nif original == \"true\":\n alephbert = BertForMaskedLM.from_pretrained('onlplab/alephbert-base')\nelse:\n alephbert = CPU_Unpickler(\n open('../AlephBERT-main/models/myFirstTune/tune_6_10.pkl', 'rb')).load()\n\n# alephbert = CPU_Unpickler(open('../../models/myFirstTune/tune_2.pkl', 'rb')).load()\n\n#print(\"after alephbert model loading\")\n\ntext = text.replace(mask, '[MASK]')\nhebrew_text = '[CLS] ' + text + ' . [SEP]'\n\ntokenized_text = alephbert_tokenizer.tokenize(hebrew_text)\nindexed_tokens = alephbert_tokenizer.convert_tokens_to_ids(tokenized_text)\n\n\n# Create the segments tensors.\nsegments_ids = [0] * len(tokenized_text)\n\n# Convert inputs to PyTorch tensors\ntokens_tensor = torch.tensor([indexed_tokens])\n\nsegments_tensors = torch.tensor([segments_ids])\n\n# Load pre-trained model (weights)\nalephbert.eval()\n\n# Predict all tokens\nwith torch.no_grad():\n predictions = alephbert(tokens_tensor, segments_tensors)\n\nmasked_index = tokenized_text.index('[MASK]')\nnum_of_res = 10\n\npredicted_sorted = torch.argsort(\n predictions[0][0, masked_index], descending=True)\ntopres = alephbert_tokenizer.convert_ids_to_tokens(\n [x.item() for x in predicted_sorted[:num_of_res]])\n\n\ndef probs_from_predictions(predictions):\n min_prediction = -predictions[0][0, masked_index][predicted_sorted[-1]]\n sum_of_predictions = torch.sum(predictions[0][0, masked_index])\n return (predictions[0][0, masked_index] + min_prediction) / (sum_of_predictions + min_prediction * len(predicted_sorted))\n\n\nprobs = probs_from_predictions(predictions)\n\nsum_of_probs = torch.sum(probs)\nassert(abs(sum_of_probs - 1) < 0.00001)\n\ntop_probs = torch.tensor(\n [probs[alephbert_tokenizer.convert_tokens_to_ids([res])[0]].item() for res in topres])\nsum_of_top = torch.sum(top_probs)\n\nrelative_probs = top_probs / sum_of_top\n\nwith_prob = list(zip(topres, relative_probs.tolist()))\n\nprint(json.dumps(with_prob))\n" ]
[ [ "torch.device", "torch.no_grad", "torch.argsort", "torch.tensor", "torch.sum" ] ]
FranckLejzerowicz/prep_songbird
[ "784412302d410a38de87d98f4852425e44f4d2e9" ]
[ "prep_songbird/_io_utils.py" ]
[ "# ----------------------------------------------------------------------------\n# Copyright (c) 2020, Franck Lejzerowicz.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file LICENSE, distributed with this software.\n# ----------------------------------------------------------------------------\n\nimport os\nimport sys\nimport yaml\nimport subprocess\nimport pandas as pd\nfrom os.path import abspath, basename, exists, isfile, isdir\n\nimport pkg_resources\nRESOURCES = pkg_resources.resource_filename(\n \"prep_songbird\", \"resources\")\n\n\ndef check_input(i_datasets_folder: str) -> str:\n \"\"\"Check that the main input folder exists\n and that it is indeed a folder, not a file.\n Returns its absolute path for unambiguous use\n in the rest of the code.\n\n Parameters\n ----------\n i_datasets_folder : str\n Main folder where datasets live.\n\n Returns\n -------\n i_datasets_folder : str\n Same folder but its absolute path.\n\n \"\"\"\n if not exists(i_datasets_folder):\n print('%s does exist\\nExiting...' % i_datasets_folder)\n sys.exit(1)\n\n i_datasets_folder = abspath(i_datasets_folder)\n if isfile(i_datasets_folder):\n print('%s is a file. Needs a folder as input\\nExiting...' %\n i_datasets_folder)\n sys.exit(1)\n return i_datasets_folder\n\n\ndef check_xpbs_install() -> None:\n \"\"\"Try to get the install path of third party tool\n Xpbs (https://github.com/FranckLejzerowicz/Xpbs).\n If it exists, nothing happens and the code proceeds.\n Otherwise, the code ends and tells what to do.\n \"\"\"\n ret_code, ret_path = subprocess.getstatusoutput('which Xpbs')\n if ret_code:\n print('Xpbs is not installed:\\n either use `--no-jobs` to not '\n 'prepare Torque/Slurm job scripts,\\n or make sure to install '\n 'Xpbs (https://github.com/FranckLejzerowicz/Xpbs) '\n 'and to edit its config.txt (see readme))\\nExiting...')\n sys.exit(1)\n else:\n with open(ret_path) as f:\n for line in f:\n break\n if line.startswith('$HOME'):\n print('Xpbs is installed but its config.txt '\n 'need editing!\\nExiting...')\n sys.exit(1)\n\n\ndef get_feature_sample_col(meta_tab: str) -> str:\n \"\"\"Get the first column of the metadata file.\n\n Parameters\n ----------\n meta_tab : str\n Data of metadata file path\n\n Returns\n -------\n first_column : str\n name of the first column in the table\n \"\"\"\n n = 0\n with open(meta_tab) as f:\n for line in f:\n n += 1\n break\n if n:\n first_column = line.split('\\t')[0]\n return first_column\n else:\n print('Empty now: %s (possibly being written elsewhere..)' % meta_tab)\n sys.exit(0)\n\n\ndef read_meta_pd(\n meta_tab: str,\n rep_col: str = 'sample_name') -> pd.DataFrame:\n \"\"\"Read metadata with first column as index.\n\n Parameters\n ----------\n meta_tab : str\n Path to the data table file\n rep_col : str\n Columns to use for index name\n\n Returns\n -------\n meta_tab_pd : pd.DataFrame\n Metadata table\n \"\"\"\n meta_tab_sam_col = get_feature_sample_col(meta_tab)\n meta_tab_pd = pd.read_csv(\n meta_tab,\n header=0,\n sep='\\t',\n dtype={meta_tab_sam_col: str},\n low_memory=False\n )\n meta_tab_pd.rename(\n columns={meta_tab_sam_col: rep_col},\n inplace=True\n )\n return meta_tab_pd\n\n\ndef read_yaml_file(file_path: str) -> dict:\n \"\"\"Simply reads a yaml and return\n its contents in a dictionary structure.\n\n Parameters\n ----------\n file_path: str\n Path to a yaml file.\n\n Returns\n -------\n yaml_dict : dict\n Dictionary object returned\n by reading the yaml file.\n (could be an empty dict)\n \"\"\"\n yaml_dict = {}\n if file_path and isfile(file_path):\n with open(file_path) as yaml_handle:\n try:\n yaml_dict = yaml.load(\n yaml_handle, Loader=yaml.FullLoader)\n except AttributeError:\n yaml_dict = yaml.load(yaml_handle)\n return yaml_dict\n\n\ndef check_run_params(\n run_params: dict,\n run_params_user: dict,\n conda_envs: set) -> dict:\n \"\"\"Verify that the keys/values passed for\n an analysis are valid.\n\n Parameters\n ----------\n run_params : dict\n Default run parameters.\n run_params_user : dict\n Passed run parameters.\n conda_envs: set\n Conda environments.\n\n Returns\n -------\n run_params : dict\n Validated run parameters.\n \"\"\"\n integer_values = [\n 'time', 'n_nodes', 'n_procs', 'mem_num'\n ]\n mem_dim = ['kb', 'mb', 'gb']\n for analysis in list(run_params_user.keys()):\n for param in list(run_params_user[analysis].keys()):\n param_val = run_params_user[analysis][param]\n if param in integer_values:\n if str(param_val).isdigit():\n run_params[analysis][param] = param_val\n elif param == 'mem_dim':\n if param_val in mem_dim:\n run_params[analysis][param] = param_val\n elif param == 'env':\n # check that qiime2 environment exists\n check_qiime2_env(param_val, conda_envs)\n run_params[analysis][param] = param_val\n return run_params\n\n\ndef get_run_params(\n p_run_params: str,\n conda_envs: set) -> dict:\n \"\"\"Get the run parameters based on the default\n values, that are possibly updated by the user.\n\n Parameters\n ----------\n p_run_params: str\n User-defined run parameters.\n conda_envs: set\n Conda environments.\n\n Returns\n -------\n run_params: dict\n Valid run parameters, which for each analysis could be\n 'time': an integer\n 'n_nodes': an integer\n 'n_procs': an integer\n 'mem_num': an integer\n 'mem_dim': either on of ['kb', 'mb', 'gb']\n 'env': an existing conda environment\n \"\"\"\n # read default run parameters (one set for each analysis)\n run_params_default_fp = '%s/run_params.yml' % RESOURCES\n run_params = read_yaml_file(run_params_default_fp)\n # update these run parameters is file is passed\n if p_run_params and isfile(p_run_params):\n run_params_update = read_yaml_file(p_run_params)\n # update these run parameters is file is passed\n run_params = check_run_params(\n run_params, run_params_update, conda_envs)\n else:\n print('Using run parameters from', run_params_default_fp)\n\n return run_params\n\n\ndef check_qiime2_env(\n qiime_env: str,\n conda_envs: set) -> None:\n \"\"\"Checks that the qiime2 environment\n exists (i.e., is in the set if discovered\n conda environments.\n\n Parameters\n ----------\n qiime_env : str\n Qiime2 conda enviroment.\n conda_envs : set\n Conda environments.\n \"\"\"\n if qiime_env not in conda_envs:\n print('%s is not an existing conda environment' % qiime_env)\n sys.exit(1)\n\n\ndef get_conda_envs(qiime_env: str) -> set:\n \"\"\"Get the names of the conda environments.\n\n Parameters\n ----------\n qiime_env : str\n Qiime2 conda enviroment.\n\n Returns\n -------\n conda_envs : set\n Conda environments.\n \"\"\"\n conda_envs = set()\n for conda_env in subprocess.getoutput('conda env list').split('\\n'):\n if len(conda_env) and conda_env[0] != '#':\n conda_envs.add(conda_env.split()[0])\n # check that qiime2 environment exists\n check_qiime2_env(qiime_env, conda_envs)\n\n return conda_envs\n\n\ndef get_prjct_anlss_nm(project_name: str) -> str:\n \"\"\"\n Get a smaller name for printing in qstat / squeue.\n\n Parameters\n ----------\n project_name : str\n Command-line passed project name.\n\n Returns\n -------\n prjct_nm : str\n Same name without the vows (\"aeiouy\").\n \"\"\"\n alpha = 'aeiouy'\n prjct_nm = ''.join(x for x in project_name if x.lower() not in alpha)\n if prjct_nm == '':\n prjct_nm = project_name\n return prjct_nm\n\n\ndef parse_g2lineage() -> dict:\n g2lineage_fp = '%s/g2lineage.txt' % RESOURCES\n g2lineage = {}\n for line in open(g2lineage_fp).readlines():\n line_split = line.strip().split('\\t')\n g2lineage[line_split[0]] = line_split[1]\n return g2lineage\n\n\ndef get_job_folder(i_datasets_folder: str, analysis: str):\n job_folder = '%s/jobs/%s' % (i_datasets_folder, analysis)\n if not isdir(job_folder):\n os.makedirs(job_folder)\n return job_folder\n\n\ndef get_analysis_folder(i_datasets_folder, analysis):\n odir = '%s/qiime/%s' % (i_datasets_folder, analysis)\n if not isdir(odir):\n os.makedirs(odir)\n return odir\n\n\ndef get_taxonomy_classifier(i_classifier: str) -> str:\n \"\"\"\n Get the full path of the reference taxonomic classifier.\n\n :param i_classifier: database to use.\n :return: path of the reference taxonomy classifier.\n \"\"\"\n if not isfile(i_classifier):\n print('%s does not exist\\nExiting...' % i_classifier)\n sys.exit(0)\n if not i_classifier.endswith('qza'):\n print('%s is not a qiime2 artefact\\nExiting...' % i_classifier)\n sys.exit(0)\n\n allowed_classifiers = [\n 'silva-132-99-nb-classifier.qza',\n 'silva-132-99-515-806-nb-classifier.qza',\n 'gg-13-8-99-nb-classifier.qza',\n 'gg-13-8-99-515-806-nb-classifier.qza'\n ]\n if basename(i_classifier) in allowed_classifiers:\n return i_classifier\n else:\n print('%s is not:\\n%s'\n 'Download: https://docs.qiime2.org/2020.2/data-resources/'\n '#taxonomy-classifiers-for-use-with-q2-feature-classifier)\\n'\n 'Exiting...' % (i_classifier,\n '\\n - %s' % '\\n - '.join(allowed_classifiers)))\n sys.exit(0)\n\n\n\n" ]
[ [ "pandas.read_csv" ] ]
Rocks-n-Code/COGCCpy
[ "93b32bff7249ed3b735b60d59915e006d713ae73" ]
[ "build/lib/COGCCpy/tops.py" ]
[ "import pandas as pd\nimport requests\nimport time\nimport re\n\nclass formation_tops:\n\n def __init__(self, apis):\n self.apis = [x.replace('-', '')[:10] for x in apis]\n state_codes = [x[:2] for x in self.apis if x[:2] != '05']\n if len(state_codes) > 0:\n raise ValueError('State code found outside of Colorado:', state_codes)\n self.df = pd.DataFrame()\n self.pull_tops()\n self.import_fmt_df()\n\n def top_parse(self, text):\n '''\n Input:\n text; str, html code from COGCC facility detail site.\n\n Output\n tops; df, DataFrame of formation tops\n '''\n # Create list of DataFrames\n df_list = pd.read_html(text)\n\n # Select last DF\n tops = df_list[-1]\n\n # Test for no tops\n if 'Formation' not in tops[0].tolist():\n print('No Tops Found')\n return pd.DataFrame()\n\n # Set column names\n i = tops[tops[0] == 'Formation'].index.values[0]\n tops.columns = [x.strip().replace(' ', '_') for x in tops.loc[i, :].tolist()]\n tops = tops[i + 1:].reset_index(drop=True)\n tops = tops[1:].reset_index(drop=True)\n\n # Format Top and Bottom column\n cols = ['Formation', 'Log_Top', 'Log_Bottom', 'Cored', 'DSTs']\n tops = tops[cols]\n for col in cols[1:3]:\n tops[col] = tops[col][tops[col].notnull()].apply(lambda x: re.sub('\\D',\n '',\n x))\n tops[col] = tops[col].astype(float)\n\n tops = tops[tops.Formation != 'No formation data to display.']\n return tops\n\n def pull_tops(self):\n '''\n Pulls tops from COGCC facility pages. Updates self.df\n '''\n baseURL = 'https://cogcc.state.co.us/cogis/FacilityDetail.asp?facid='\n\n total = len(self.apis)\n i = 0\n for api in self.apis:\n i += 1\n prec = str(int(100 * i / total)) + '% complete '\n print(api, prec, end='\\r')\n try:\n url = baseURL + api.replace('-', '')[2:] #+ tailURL\n r = requests.get(url)\n\n if r.status_code == 200:\n formations = self.top_parse(r.text)\n formations['API'] = api\n self.df = pd.concat([self.df, formations],\n ignore_index=True)\n time.sleep(5) # Wait 5 sec.\n else:\n print(api, ':', r.status_code)\n except Exception as e:\n print('Error:', api, e)\n\n def import_fmt_df(self):\n df = self.df.copy()\n tops = sorted(df.Formation[df.Log_Top.notnull()].unique().tolist())\n bases = sorted(df.Formation[df.Log_Top.notnull()].unique().tolist())\n for top in tops:\n df[top.replace(' ','_')] = df.Log_Top[(df.Formation == top)&(df.Log_Top.notnull())]\n for base in bases:\n df[base.replace(' ','_') + '_base'] = df.Log_Bottom[(df.Formation == base)&(df.Log_Bottom.notnull())]\n\n cols = sorted([x.replace(' ','_') for x in tops] + [x.replace(' ','_') + '_base' for x in bases])\n cols = ['API'] + cols\n self.fmt_df = df" ]
[ [ "pandas.DataFrame", "pandas.read_html", "pandas.concat" ] ]
punit-bhatt/cmu-10601-intro-to-ml
[ "a4b7bdb27a388a2996e3f4dac99f34156ff9f01e" ]
[ "assignments/solutions/hw8/handout/python/rendering.py" ]
[ "\"\"\"\r\n2D rendering framework\r\nTaken from: https://github.com/openai/gym/blob/master/gym/envs/classic_control/rendering.py\r\n\"\"\"\r\nfrom __future__ import division\r\nimport os\r\nimport six\r\nimport sys\r\n\r\nif \"Apple\" in sys.version:\r\n if 'DYLD_FALLBACK_LIBRARY_PATH' in os.environ:\r\n os.environ['DYLD_FALLBACK_LIBRARY_PATH'] += ':/usr/lib'\r\n # (JDS 2016/04/15): avoid bug on Anaconda 2.3.0 / Yosemite\r\n\r\nclass Error(Exception):\r\n pass\r\n\r\ntry:\r\n import pyglet\r\nexcept ImportError as e:\r\n raise ImportError('''\r\n Cannot import pyglet.\r\n HINT: you can install pyglet directly via 'pip install pyglet' or 'conda install -c conda-forge pyglet'.\r\n ''')\r\n\r\ntry:\r\n from pyglet.gl import *\r\nexcept ImportError as e:\r\n raise ImportError('''\r\n Error occured while running `from pyglet.gl import *`\r\n HINT: make sure you have OpenGL install. On Ubuntu, you can run 'apt-get install python-opengl'.\r\n If you're running on a server, you may need a virtual frame buffer; something like this should work:\r\n 'xvfb-run -s \\\"-screen 0 1400x900x24\\\" python <your_script.py>'\r\n ''')\r\n\r\nimport math\r\nimport numpy as np\r\n\r\nRAD2DEG = 57.29577951308232\r\n\r\ndef get_display(spec):\r\n \"\"\"Convert a display specification (such as :0) into an actual Display\r\n object.\r\n\r\n Pyglet only supports multiple Displays on Linux.\r\n \"\"\"\r\n if spec is None:\r\n return None\r\n elif isinstance(spec, six.string_types):\r\n return pyglet.canvas.Display(spec)\r\n else:\r\n raise Error('Invalid display specification: {}. (Must be a string like :0 or None.)'.format(spec))\r\n\r\nclass Viewer(object):\r\n def __init__(self, width, height, display=None):\r\n display = get_display(display)\r\n\r\n self.width = width\r\n self.height = height\r\n self.window = pyglet.window.Window(width=width, height=height, display=display)\r\n self.window.on_close = self.window_closed_by_user\r\n self.isopen = True\r\n self.geoms = []\r\n self.onetime_geoms = []\r\n self.transform = Transform()\r\n\r\n glEnable(GL_BLEND)\r\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)\r\n\r\n def close(self):\r\n self.window.close()\r\n\r\n def window_closed_by_user(self):\r\n self.isopen = False\r\n\r\n def set_bounds(self, left, right, bottom, top):\r\n assert right > left and top > bottom\r\n scalex = self.width/(right-left)\r\n scaley = self.height/(top-bottom)\r\n self.transform = Transform(\r\n translation=(-left*scalex, -bottom*scaley),\r\n scale=(scalex, scaley))\r\n\r\n def add_geom(self, geom):\r\n self.geoms.append(geom)\r\n\r\n def add_onetime(self, geom):\r\n self.onetime_geoms.append(geom)\r\n\r\n def render(self, return_rgb_array=False):\r\n glClearColor(1,1,1,1)\r\n self.window.clear()\r\n self.window.switch_to()\r\n self.window.dispatch_events()\r\n self.transform.enable()\r\n for geom in self.geoms:\r\n geom.render()\r\n for geom in self.onetime_geoms:\r\n geom.render()\r\n self.transform.disable()\r\n arr = None\r\n if return_rgb_array:\r\n buffer = pyglet.image.get_buffer_manager().get_color_buffer()\r\n image_data = buffer.get_image_data()\r\n arr = np.frombuffer(image_data.data, dtype=np.uint8)\r\n # In https://github.com/openai/gym-http-api/issues/2, we\r\n # discovered that someone using Xmonad on Arch was having\r\n # a window of size 598 x 398, though a 600 x 400 window\r\n # was requested. (Guess Xmonad was preserving a pixel for\r\n # the boundary.) So we use the buffer height/width rather\r\n # than the requested one.\r\n arr = arr.reshape(buffer.height, buffer.width, 4)\r\n arr = arr[::-1,:,0:3]\r\n self.window.flip()\r\n self.onetime_geoms = []\r\n return arr if return_rgb_array else self.isopen\r\n\r\n # Convenience\r\n def draw_circle(self, radius=10, res=30, filled=True, **attrs):\r\n geom = make_circle(radius=radius, res=res, filled=filled)\r\n _add_attrs(geom, attrs)\r\n self.add_onetime(geom)\r\n return geom\r\n\r\n def draw_polygon(self, v, filled=True, **attrs):\r\n geom = make_polygon(v=v, filled=filled)\r\n _add_attrs(geom, attrs)\r\n self.add_onetime(geom)\r\n return geom\r\n\r\n def draw_polyline(self, v, **attrs):\r\n geom = make_polyline(v=v)\r\n _add_attrs(geom, attrs)\r\n self.add_onetime(geom)\r\n return geom\r\n\r\n def draw_line(self, start, end, **attrs):\r\n geom = Line(start, end)\r\n _add_attrs(geom, attrs)\r\n self.add_onetime(geom)\r\n return geom\r\n\r\n def get_array(self):\r\n self.window.flip()\r\n image_data = pyglet.image.get_buffer_manager().get_color_buffer().get_image_data()\r\n self.window.flip()\r\n arr = np.fromstring(image_data.data, dtype=np.uint8, sep='')\r\n arr = arr.reshape(self.height, self.width, 4)\r\n return arr[::-1,:,0:3]\r\n\r\n def __del__(self):\r\n self.close()\r\n\r\ndef _add_attrs(geom, attrs):\r\n if \"color\" in attrs:\r\n geom.set_color(*attrs[\"color\"])\r\n if \"linewidth\" in attrs:\r\n geom.set_linewidth(attrs[\"linewidth\"])\r\n\r\nclass Geom(object):\r\n def __init__(self):\r\n self._color=Color((0, 0, 0, 1.0))\r\n self.attrs = [self._color]\r\n def render(self):\r\n for attr in reversed(self.attrs):\r\n attr.enable()\r\n self.render1()\r\n for attr in self.attrs:\r\n attr.disable()\r\n def render1(self):\r\n raise NotImplementedError\r\n def add_attr(self, attr):\r\n self.attrs.append(attr)\r\n def set_color(self, r, g, b):\r\n self._color.vec4 = (r, g, b, 1)\r\n\r\nclass Attr(object):\r\n def enable(self):\r\n raise NotImplementedError\r\n def disable(self):\r\n pass\r\n\r\nclass Transform(Attr):\r\n def __init__(self, translation=(0.0, 0.0), rotation=0.0, scale=(1,1)):\r\n self.set_translation(*translation)\r\n self.set_rotation(rotation)\r\n self.set_scale(*scale)\r\n def enable(self):\r\n glPushMatrix()\r\n glTranslatef(self.translation[0], self.translation[1], 0) # translate to GL loc ppint\r\n glRotatef(RAD2DEG * self.rotation, 0, 0, 1.0)\r\n glScalef(self.scale[0], self.scale[1], 1)\r\n def disable(self):\r\n glPopMatrix()\r\n def set_translation(self, newx, newy):\r\n self.translation = (float(newx), float(newy))\r\n def set_rotation(self, new):\r\n self.rotation = float(new)\r\n def set_scale(self, newx, newy):\r\n self.scale = (float(newx), float(newy))\r\n\r\nclass Color(Attr):\r\n def __init__(self, vec4):\r\n self.vec4 = vec4\r\n def enable(self):\r\n glColor4f(*self.vec4)\r\n\r\nclass LineStyle(Attr):\r\n def __init__(self, style):\r\n self.style = style\r\n def enable(self):\r\n glEnable(GL_LINE_STIPPLE)\r\n glLineStipple(1, self.style)\r\n def disable(self):\r\n glDisable(GL_LINE_STIPPLE)\r\n\r\nclass LineWidth(Attr):\r\n def __init__(self, stroke):\r\n self.stroke = stroke\r\n def enable(self):\r\n glLineWidth(self.stroke)\r\n\r\nclass Point(Geom):\r\n def __init__(self):\r\n Geom.__init__(self)\r\n def render1(self):\r\n glBegin(GL_POINTS) # draw point\r\n glVertex3f(0.0, 0.0, 0.0)\r\n glEnd()\r\n\r\nclass FilledPolygon(Geom):\r\n def __init__(self, v):\r\n Geom.__init__(self)\r\n self.v = v\r\n def render1(self):\r\n if len(self.v) == 4 : glBegin(GL_QUADS)\r\n elif len(self.v) > 4 : glBegin(GL_POLYGON)\r\n else: glBegin(GL_TRIANGLES)\r\n for p in self.v:\r\n glVertex3f(p[0], p[1],0) # draw each vertex\r\n glEnd()\r\n\r\ndef make_circle(radius=10, res=30, filled=True):\r\n points = []\r\n for i in range(res):\r\n ang = 2*math.pi*i / res\r\n points.append((math.cos(ang)*radius, math.sin(ang)*radius))\r\n if filled:\r\n return FilledPolygon(points)\r\n else:\r\n return PolyLine(points, True)\r\n\r\ndef make_polygon(v, filled=True):\r\n if filled: return FilledPolygon(v)\r\n else: return PolyLine(v, True)\r\n\r\ndef make_polyline(v):\r\n return PolyLine(v, False)\r\n\r\ndef make_capsule(length, width):\r\n l, r, t, b = 0, length, width/2, -width/2\r\n box = make_polygon([(l,b), (l,t), (r,t), (r,b)])\r\n circ0 = make_circle(width/2)\r\n circ1 = make_circle(width/2)\r\n circ1.add_attr(Transform(translation=(length, 0)))\r\n geom = Compound([box, circ0, circ1])\r\n return geom\r\n\r\nclass Compound(Geom):\r\n def __init__(self, gs):\r\n Geom.__init__(self)\r\n self.gs = gs\r\n for g in self.gs:\r\n g.attrs = [a for a in g.attrs if not isinstance(a, Color)]\r\n def render1(self):\r\n for g in self.gs:\r\n g.render()\r\n\r\nclass PolyLine(Geom):\r\n def __init__(self, v, close):\r\n Geom.__init__(self)\r\n self.v = v\r\n self.close = close\r\n self.linewidth = LineWidth(1)\r\n self.add_attr(self.linewidth)\r\n def render1(self):\r\n glBegin(GL_LINE_LOOP if self.close else GL_LINE_STRIP)\r\n for p in self.v:\r\n glVertex3f(p[0], p[1],0) # draw each vertex\r\n glEnd()\r\n def set_linewidth(self, x):\r\n self.linewidth.stroke = x\r\n\r\nclass Line(Geom):\r\n def __init__(self, start=(0.0, 0.0), end=(0.0, 0.0)):\r\n Geom.__init__(self)\r\n self.start = start\r\n self.end = end\r\n self.linewidth = LineWidth(1)\r\n self.add_attr(self.linewidth)\r\n\r\n def render1(self):\r\n glBegin(GL_LINES)\r\n glVertex2f(*self.start)\r\n glVertex2f(*self.end)\r\n glEnd()\r\n\r\nclass Image(Geom):\r\n def __init__(self, fname, width, height):\r\n Geom.__init__(self)\r\n self.width = width\r\n self.height = height\r\n img = pyglet.image.load(fname)\r\n self.img = img\r\n self.flip = False\r\n def render1(self):\r\n self.img.blit(-self.width/2, -self.height/2, width=self.width, height=self.height)\r\n\r\n# ================================================================\r\n\r\nclass SimpleImageViewer(object):\r\n def __init__(self, display=None, maxwidth=500):\r\n self.window = None\r\n self.isopen = False\r\n self.display = display\r\n self.maxwidth = maxwidth\r\n def imshow(self, arr):\r\n if self.window is None:\r\n height, width, _channels = arr.shape\r\n if width > self.maxwidth:\r\n scale = self.maxwidth / width\r\n width = int(scale * width)\r\n height = int(scale * height)\r\n self.window = pyglet.window.Window(width=width, height=height, \r\n display=self.display, vsync=False, resizable=True) \r\n self.width = width\r\n self.height = height\r\n self.isopen = True\r\n\r\n @self.window.event\r\n def on_resize(width, height):\r\n self.width = width\r\n self.height = height\r\n\r\n @self.window.event\r\n def on_close():\r\n self.isopen = False\r\n\r\n assert len(arr.shape) == 3, \"You passed in an image with the wrong number shape\"\r\n image = pyglet.image.ImageData(arr.shape[1], arr.shape[0], \r\n 'RGB', arr.tobytes(), pitch=arr.shape[1]*-3)\r\n gl.glTexParameteri(gl.GL_TEXTURE_2D, \r\n gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST)\r\n texture = image.get_texture()\r\n texture.width = self.width\r\n texture.height = self.height\r\n self.window.clear()\r\n self.window.switch_to()\r\n self.window.dispatch_events()\r\n texture.blit(0, 0) # draw\r\n self.window.flip()\r\n def close(self):\r\n if self.isopen and sys.meta_path:\r\n # ^^^ check sys.meta_path to avoid 'ImportError: sys.meta_path is None, Python is likely shutting down'\r\n self.window.close()\r\n self.isopen = False\r\n\r\n def __del__(self):\r\n self.close()" ]
[ [ "numpy.fromstring", "numpy.frombuffer" ] ]
wphicks/xgboost
[ "3912f3de06bcc76295d18dab7f0a5f68e4e460c0" ]
[ "python-package/xgboost/data.py" ]
[ "# pylint: disable=too-many-arguments, too-many-branches\n# pylint: disable=too-many-return-statements, import-error\n'''Data dispatching for DMatrix.'''\nimport ctypes\nimport json\nimport warnings\n\nimport numpy as np\n\nfrom .core import c_array, _LIB, _check_call, c_str\nfrom .core import DataIter, DeviceQuantileDMatrix, DMatrix\nfrom .compat import lazy_isinstance, os_fspath, os_PathLike\n\nc_bst_ulong = ctypes.c_uint64 # pylint: disable=invalid-name\n\n\ndef _warn_unused_missing(data, missing):\n if (missing is not None) and (not np.isnan(missing)):\n warnings.warn(\n '`missing` is not used for current input data type:' +\n str(type(data)), UserWarning)\n\n\ndef _check_complex(data):\n '''Test whether data is complex using `dtype` attribute.'''\n complex_dtypes = (np.complex128, np.complex64,\n np.cfloat, np.cdouble, np.clongdouble)\n if hasattr(data, 'dtype') and data.dtype in complex_dtypes:\n raise ValueError('Complex data not supported')\n\n\ndef _is_scipy_csr(data):\n try:\n import scipy\n except ImportError:\n scipy = None\n return False\n return isinstance(data, scipy.sparse.csr_matrix)\n\n\ndef _from_scipy_csr(data, missing, feature_names, feature_types):\n '''Initialize data from a CSR matrix.'''\n if len(data.indices) != len(data.data):\n raise ValueError('length mismatch: {} vs {}'.format(\n len(data.indices), len(data.data)))\n _warn_unused_missing(data, missing)\n handle = ctypes.c_void_p()\n _check_call(_LIB.XGDMatrixCreateFromCSREx(\n c_array(ctypes.c_size_t, data.indptr),\n c_array(ctypes.c_uint, data.indices),\n c_array(ctypes.c_float, data.data),\n ctypes.c_size_t(len(data.indptr)),\n ctypes.c_size_t(len(data.data)),\n ctypes.c_size_t(data.shape[1]),\n ctypes.byref(handle)))\n return handle, feature_names, feature_types\n\n\ndef _is_scipy_csc(data):\n try:\n import scipy\n except ImportError:\n scipy = None\n return False\n return isinstance(data, scipy.sparse.csc_matrix)\n\n\ndef _from_scipy_csc(data, missing, feature_names, feature_types):\n if len(data.indices) != len(data.data):\n raise ValueError('length mismatch: {} vs {}'.format(\n len(data.indices), len(data.data)))\n _warn_unused_missing(data, missing)\n handle = ctypes.c_void_p()\n _check_call(_LIB.XGDMatrixCreateFromCSCEx(\n c_array(ctypes.c_size_t, data.indptr),\n c_array(ctypes.c_uint, data.indices),\n c_array(ctypes.c_float, data.data),\n ctypes.c_size_t(len(data.indptr)),\n ctypes.c_size_t(len(data.data)),\n ctypes.c_size_t(data.shape[0]),\n ctypes.byref(handle)))\n return handle, feature_names, feature_types\n\n\ndef _is_numpy_array(data):\n return isinstance(data, (np.ndarray, np.matrix))\n\n\ndef _maybe_np_slice(data, dtype):\n '''Handle numpy slice. This can be removed if we use __array_interface__.\n '''\n try:\n if not data.flags.c_contiguous:\n warnings.warn(\n \"Use subset (sliced data) of np.ndarray is not recommended \" +\n \"because it will generate extra copies and increase \" +\n \"memory consumption\")\n data = np.array(data, copy=True, dtype=dtype)\n else:\n data = np.array(data, copy=False, dtype=dtype)\n except AttributeError:\n data = np.array(data, copy=False, dtype=dtype)\n return data\n\n\ndef _transform_np_array(data: np.ndarray):\n if not isinstance(data, np.ndarray) and hasattr(data, '__array__'):\n data = np.array(data, copy=False)\n if len(data.shape) != 2:\n raise ValueError('Expecting 2 dimensional numpy.ndarray, got: ',\n data.shape)\n # flatten the array by rows and ensure it is float32. we try to avoid\n # data copies if possible (reshape returns a view when possible and we\n # explicitly tell np.array to try and avoid copying)\n flatten = np.array(data.reshape(data.size), copy=False,\n dtype=np.float32)\n flatten = _maybe_np_slice(flatten, np.float32)\n _check_complex(data)\n return flatten\n\n\ndef _from_numpy_array(data, missing, nthread, feature_names, feature_types):\n \"\"\"Initialize data from a 2-D numpy matrix.\n\n If ``mat`` does not have ``order='C'`` (aka row-major) or is\n not contiguous, a temporary copy will be made.\n\n If ``mat`` does not have ``dtype=numpy.float32``, a temporary copy will\n be made.\n\n So there could be as many as two temporary data copies; be mindful of\n input layout and type if memory use is a concern.\n\n \"\"\"\n flatten = _transform_np_array(data)\n handle = ctypes.c_void_p()\n _check_call(_LIB.XGDMatrixCreateFromMat_omp(\n flatten.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),\n c_bst_ulong(data.shape[0]),\n c_bst_ulong(data.shape[1]),\n ctypes.c_float(missing),\n ctypes.byref(handle),\n ctypes.c_int(nthread)))\n return handle, feature_names, feature_types\n\n\ndef _is_pandas_df(data):\n try:\n import pandas as pd\n except ImportError:\n return False\n return isinstance(data, pd.DataFrame)\n\ndef _is_modin_df(data):\n try:\n import modin.pandas as pd\n except ImportError:\n return False\n return isinstance(data, pd.DataFrame)\n\n\n_pandas_dtype_mapper = {\n 'int8': 'int',\n 'int16': 'int',\n 'int32': 'int',\n 'int64': 'int',\n 'uint8': 'int',\n 'uint16': 'int',\n 'uint32': 'int',\n 'uint64': 'int',\n 'float16': 'float',\n 'float32': 'float',\n 'float64': 'float',\n 'bool': 'i'\n}\n\n\ndef _transform_pandas_df(data, feature_names=None, feature_types=None,\n meta=None, meta_type=None):\n from pandas import MultiIndex, Int64Index\n from pandas.api.types import is_sparse\n data_dtypes = data.dtypes\n if not all(dtype.name in _pandas_dtype_mapper or is_sparse(dtype)\n for dtype in data_dtypes):\n bad_fields = [\n str(data.columns[i]) for i, dtype in enumerate(data_dtypes)\n if dtype.name not in _pandas_dtype_mapper\n ]\n\n msg = \"\"\"DataFrame.dtypes for data must be int, float or bool.\n Did not expect the data types in fields \"\"\"\n raise ValueError(msg + ', '.join(bad_fields))\n\n if feature_names is None and meta is None:\n if isinstance(data.columns, MultiIndex):\n feature_names = [\n ' '.join([str(x) for x in i]) for i in data.columns\n ]\n elif isinstance(data.columns, Int64Index):\n feature_names = list(map(str, data.columns))\n else:\n feature_names = data.columns.format()\n\n if feature_types is None and meta is None:\n feature_types = []\n for dtype in data_dtypes:\n if is_sparse(dtype):\n feature_types.append(_pandas_dtype_mapper[\n dtype.subtype.name])\n else:\n feature_types.append(_pandas_dtype_mapper[dtype.name])\n\n if meta and len(data.columns) > 1:\n raise ValueError(\n 'DataFrame for {meta} cannot have multiple columns'.format(\n meta=meta))\n\n dtype = meta_type if meta_type else np.float32\n data = np.ascontiguousarray(data.values, dtype=dtype)\n\n return data, feature_names, feature_types\n\n\ndef _from_pandas_df(data, missing, nthread, feature_names, feature_types):\n data, feature_names, feature_types = _transform_pandas_df(\n data, feature_names, feature_types)\n return _from_numpy_array(data, missing, nthread, feature_names,\n feature_types)\n\n\ndef _is_pandas_series(data):\n try:\n import pandas as pd\n except ImportError:\n return False\n return isinstance(data, pd.Series)\n\ndef _is_modin_series(data):\n try:\n import modin.pandas as pd\n except ImportError:\n return False\n return isinstance(data, pd.Series)\n\n\ndef _from_pandas_series(data, missing, nthread, feature_types, feature_names):\n return _from_numpy_array(data.values.astype('float'), missing, nthread,\n feature_names, feature_types)\n\n\ndef _is_dt_df(data):\n return lazy_isinstance(data, 'datatable', 'Frame') or \\\n lazy_isinstance(data, 'datatable', 'DataTable')\n\n\n_dt_type_mapper = {'bool': 'bool', 'int': 'int', 'real': 'float'}\n_dt_type_mapper2 = {'bool': 'i', 'int': 'int', 'real': 'float'}\n\n\ndef _transform_dt_df(data, feature_names, feature_types, meta=None,\n meta_type=None):\n \"\"\"Validate feature names and types if data table\"\"\"\n if meta and data.shape[1] > 1:\n raise ValueError(\n 'DataTable for label or weight cannot have multiple columns')\n if meta:\n # below requires new dt version\n # extract first column\n data = data.to_numpy()[:, 0].astype(meta_type)\n return data, None, None\n\n data_types_names = tuple(lt.name for lt in data.ltypes)\n bad_fields = [data.names[i]\n for i, type_name in enumerate(data_types_names)\n if type_name not in _dt_type_mapper]\n if bad_fields:\n msg = \"\"\"DataFrame.types for data must be int, float or bool.\n Did not expect the data types in fields \"\"\"\n raise ValueError(msg + ', '.join(bad_fields))\n\n if feature_names is None and meta is None:\n feature_names = data.names\n\n # always return stypes for dt ingestion\n if feature_types is not None:\n raise ValueError(\n 'DataTable has own feature types, cannot pass them in.')\n feature_types = np.vectorize(_dt_type_mapper2.get)(\n data_types_names).tolist()\n\n return data, feature_names, feature_types\n\n\ndef _from_dt_df(data, missing, nthread, feature_names, feature_types):\n data, feature_names, feature_types = _transform_dt_df(\n data, feature_names, feature_types, None, None)\n\n ptrs = (ctypes.c_void_p * data.ncols)()\n if hasattr(data, \"internal\") and hasattr(data.internal, \"column\"):\n # datatable>0.8.0\n for icol in range(data.ncols):\n col = data.internal.column(icol)\n ptr = col.data_pointer\n ptrs[icol] = ctypes.c_void_p(ptr)\n else:\n # datatable<=0.8.0\n from datatable.internal import \\\n frame_column_data_r # pylint: disable=no-name-in-module\n for icol in range(data.ncols):\n ptrs[icol] = frame_column_data_r(data, icol)\n\n # always return stypes for dt ingestion\n feature_type_strings = (ctypes.c_char_p * data.ncols)()\n for icol in range(data.ncols):\n feature_type_strings[icol] = ctypes.c_char_p(\n data.stypes[icol].name.encode('utf-8'))\n\n _warn_unused_missing(data, missing)\n handle = ctypes.c_void_p()\n _check_call(_LIB.XGDMatrixCreateFromDT(\n ptrs, feature_type_strings,\n c_bst_ulong(data.shape[0]),\n c_bst_ulong(data.shape[1]),\n ctypes.byref(handle),\n ctypes.c_int(nthread)))\n return handle, feature_names, feature_types\n\n\ndef _is_cudf_df(data):\n try:\n import cudf\n except ImportError:\n return False\n return hasattr(cudf, 'DataFrame') and isinstance(data, cudf.DataFrame)\n\n\ndef _cudf_array_interfaces(data):\n '''Extract CuDF __cuda_array_interface__'''\n interfaces = []\n if _is_cudf_ser(data):\n interfaces.append(data.__cuda_array_interface__)\n else:\n for col in data:\n interface = data[col].__cuda_array_interface__\n if 'mask' in interface:\n interface['mask'] = interface['mask'].__cuda_array_interface__\n interfaces.append(interface)\n interfaces_str = bytes(json.dumps(interfaces, indent=2), 'utf-8')\n return interfaces_str\n\n\ndef _transform_cudf_df(data, feature_names, feature_types):\n if feature_names is None:\n if _is_cudf_ser(data):\n feature_names = [data.name]\n elif lazy_isinstance(\n data.columns, 'cudf.core.multiindex', 'MultiIndex'):\n feature_names = [\n ' '.join([str(x) for x in i])\n for i in data.columns\n ]\n else:\n feature_names = data.columns.format()\n if feature_types is None:\n if _is_cudf_ser(data):\n dtypes = [data.dtype]\n else:\n dtypes = data.dtypes\n feature_types = [_pandas_dtype_mapper[d.name]\n for d in dtypes]\n return data, feature_names, feature_types\n\n\ndef _from_cudf_df(data, missing, nthread, feature_names, feature_types):\n data, feature_names, feature_types = _transform_cudf_df(\n data, feature_names, feature_types)\n interfaces_str = _cudf_array_interfaces(data)\n handle = ctypes.c_void_p()\n _check_call(\n _LIB.XGDMatrixCreateFromArrayInterfaceColumns(\n interfaces_str,\n ctypes.c_float(missing),\n ctypes.c_int(nthread),\n ctypes.byref(handle)))\n return handle, feature_names, feature_types\n\n\ndef _is_cudf_ser(data):\n try:\n import cudf\n except ImportError:\n return False\n return isinstance(data, cudf.Series)\n\n\ndef _is_cupy_array(data):\n try:\n import cupy\n except ImportError:\n return False\n return isinstance(data, cupy.ndarray)\n\n\ndef _transform_cupy_array(data):\n if not hasattr(data, '__cuda_array_interface__') and hasattr(\n data, '__array__'):\n import cupy # pylint: disable=import-error\n data = cupy.array(data, copy=False)\n return data\n\n\ndef _from_cupy_array(data, missing, nthread, feature_names, feature_types):\n \"\"\"Initialize DMatrix from cupy ndarray.\"\"\"\n data = _transform_cupy_array(data)\n interface = data.__cuda_array_interface__\n if 'mask' in interface:\n interface['mask'] = interface['mask'].__cuda_array_interface__\n interface_str = bytes(json.dumps(interface, indent=2), 'utf-8')\n\n handle = ctypes.c_void_p()\n _check_call(\n _LIB.XGDMatrixCreateFromArrayInterface(\n interface_str,\n ctypes.c_float(missing),\n ctypes.c_int(nthread),\n ctypes.byref(handle)))\n return handle, feature_names, feature_types\n\n\ndef _is_cupy_csr(data):\n try:\n import cupyx\n except ImportError:\n return False\n return isinstance(data, cupyx.scipy.sparse.csr_matrix)\n\n\ndef _is_cupy_csc(data):\n try:\n import cupyx\n except ImportError:\n return False\n return isinstance(data, cupyx.scipy.sparse.csc_matrix)\n\n\ndef _is_dlpack(data):\n return 'PyCapsule' in str(type(data)) and \"dltensor\" in str(data)\n\n\ndef _transform_dlpack(data):\n from cupy import fromDlpack # pylint: disable=E0401\n assert 'used_dltensor' not in str(data)\n data = fromDlpack(data)\n return data\n\n\ndef _from_dlpack(data, missing, nthread, feature_names, feature_types):\n data = _transform_dlpack(data)\n return _from_cupy_array(data, missing, nthread, feature_names,\n feature_types)\n\n\ndef _is_uri(data):\n return isinstance(data, (str, os_PathLike))\n\n\ndef _from_uri(data, missing, feature_names, feature_types):\n _warn_unused_missing(data, missing)\n handle = ctypes.c_void_p()\n _check_call(_LIB.XGDMatrixCreateFromFile(c_str(os_fspath(data)),\n ctypes.c_int(1),\n ctypes.byref(handle)))\n return handle, feature_names, feature_types\n\n\ndef _is_list(data):\n return isinstance(data, list)\n\n\ndef _from_list(data, missing, feature_names, feature_types):\n raise TypeError('List input data is not supported for data')\n\n\ndef _is_tuple(data):\n return isinstance(data, tuple)\n\n\ndef _from_tuple(data, missing, feature_names, feature_types):\n return _from_list(data, missing, feature_names, feature_types)\n\n\ndef _is_iter(data):\n return isinstance(data, DataIter)\n\n\ndef _has_array_protocol(data):\n return hasattr(data, '__array__')\n\n\ndef dispatch_data_backend(data, missing, threads,\n feature_names, feature_types):\n '''Dispatch data for DMatrix.'''\n if _is_scipy_csr(data):\n return _from_scipy_csr(data, missing, feature_names, feature_types)\n if _is_scipy_csc(data):\n return _from_scipy_csc(data, missing, feature_names, feature_types)\n if _is_numpy_array(data):\n return _from_numpy_array(data, missing, threads, feature_names,\n feature_types)\n if _is_uri(data):\n return _from_uri(data, missing, feature_names, feature_types)\n if _is_list(data):\n return _from_list(data, missing, feature_names, feature_types)\n if _is_tuple(data):\n return _from_tuple(data, missing, feature_names, feature_types)\n if _is_pandas_df(data):\n return _from_pandas_df(data, missing, threads,\n feature_names, feature_types)\n if _is_pandas_series(data):\n return _from_pandas_series(data, missing, threads, feature_names,\n feature_types)\n if _is_cudf_df(data):\n return _from_cudf_df(data, missing, threads, feature_names,\n feature_types)\n if _is_cudf_ser(data):\n return _from_cudf_df(data, missing, threads, feature_names,\n feature_types)\n if _is_cupy_array(data):\n return _from_cupy_array(data, missing, threads, feature_names,\n feature_types)\n if _is_cupy_csr(data):\n raise TypeError('cupyx CSR is not supported yet.')\n if _is_cupy_csc(data):\n raise TypeError('cupyx CSC is not supported yet.')\n if _is_dlpack(data):\n return _from_dlpack(data, missing, threads, feature_names,\n feature_types)\n if _is_dt_df(data):\n _warn_unused_missing(data, missing)\n return _from_dt_df(data, missing, threads, feature_names,\n feature_types)\n if _is_modin_df(data):\n return _from_pandas_df(data, missing, threads,\n feature_names, feature_types)\n if _is_modin_series(data):\n return _from_pandas_series(data, missing, threads, feature_names,\n feature_types)\n if _has_array_protocol(data):\n pass\n raise TypeError('Not supported type for data.' + str(type(data)))\n\n\ndef _to_data_type(dtype: str, name: str):\n dtype_map = {'float32': 1, 'float64': 2, 'uint32': 3, 'uint64': 4}\n if dtype not in dtype_map.keys():\n raise TypeError(\n f'Expecting float32, float64, uint32, uint64, got {dtype} ' +\n f'for {name}.')\n return dtype_map[dtype]\n\n\ndef _validate_meta_shape(data):\n if hasattr(data, 'shape'):\n assert len(data.shape) == 1 or (\n len(data.shape) == 2 and\n (data.shape[1] == 0 or data.shape[1] == 1))\n\n\ndef _meta_from_numpy(data, field, dtype, handle):\n data = _maybe_np_slice(data, dtype)\n interface = data.__array_interface__\n assert interface.get('mask', None) is None, 'Masked array is not supported'\n size = data.shape[0]\n\n c_type = _to_data_type(str(data.dtype), field)\n ptr = interface['data'][0]\n ptr = ctypes.c_void_p(ptr)\n _check_call(_LIB.XGDMatrixSetDenseInfo(\n handle,\n c_str(field),\n ptr,\n c_bst_ulong(size),\n c_type\n ))\n\n\ndef _meta_from_list(data, field, dtype, handle):\n data = np.array(data)\n _meta_from_numpy(data, field, dtype, handle)\n\n\ndef _meta_from_tuple(data, field, dtype, handle):\n return _meta_from_list(data, field, dtype, handle)\n\n\ndef _meta_from_cudf_df(data, field, handle):\n if len(data.columns) != 1:\n raise ValueError(\n 'Expecting meta-info to contain a single column')\n data = data[data.columns[0]]\n\n interface = bytes(json.dumps([data.__cuda_array_interface__],\n indent=2), 'utf-8')\n _check_call(_LIB.XGDMatrixSetInfoFromInterface(handle,\n c_str(field),\n interface))\n\n\ndef _meta_from_cudf_series(data, field, handle):\n interface = bytes(json.dumps([data.__cuda_array_interface__],\n indent=2), 'utf-8')\n _check_call(_LIB.XGDMatrixSetInfoFromInterface(handle,\n c_str(field),\n interface))\n\n\ndef _meta_from_cupy_array(data, field, handle):\n data = _transform_cupy_array(data)\n interface = bytes(json.dumps([data.__cuda_array_interface__],\n indent=2), 'utf-8')\n _check_call(_LIB.XGDMatrixSetInfoFromInterface(handle,\n c_str(field),\n interface))\n\n\ndef _meta_from_dt(data, field, dtype, handle):\n data, _, _ = _transform_dt_df(data, None, None)\n _meta_from_numpy(data, field, dtype, handle)\n\n\ndef dispatch_meta_backend(matrix: DMatrix, data, name: str, dtype: str = None):\n '''Dispatch for meta info.'''\n handle = matrix.handle\n _validate_meta_shape(data)\n if data is None:\n return\n if _is_list(data):\n _meta_from_list(data, name, dtype, handle)\n return\n if _is_tuple(data):\n _meta_from_tuple(data, name, dtype, handle)\n return\n if _is_numpy_array(data):\n _meta_from_numpy(data, name, dtype, handle)\n return\n if _is_pandas_df(data):\n data, _, _ = _transform_pandas_df(data, meta=name, meta_type=dtype)\n _meta_from_numpy(data, name, dtype, handle)\n return\n if _is_pandas_series(data):\n data = data.values.astype('float')\n assert len(data.shape) == 1 or data.shape[1] == 0 or data.shape[1] == 1\n _meta_from_numpy(data, name, dtype, handle)\n return\n if _is_dlpack(data):\n data = _transform_dlpack(data)\n _meta_from_cupy_array(data, name, handle)\n return\n if _is_cupy_array(data):\n _meta_from_cupy_array(data, name, handle)\n return\n if _is_cudf_ser(data):\n _meta_from_cudf_series(data, name, handle)\n return\n if _is_cudf_df(data):\n _meta_from_cudf_df(data, name, handle)\n return\n if _is_dt_df(data):\n _meta_from_dt(data, name, dtype, handle)\n return\n if _is_modin_df(data):\n data, _, _ = _transform_pandas_df(data, meta=name, meta_type=dtype)\n _meta_from_numpy(data, name, dtype, handle)\n return\n if _is_modin_series(data):\n data = data.values.astype('float')\n assert len(data.shape) == 1 or data.shape[1] == 0 or data.shape[1] == 1\n _meta_from_numpy(data, name, dtype, handle)\n return\n if _has_array_protocol(data):\n pass\n raise TypeError('Unsupported type for ' + name, str(type(data)))\n\n\nclass SingleBatchInternalIter(DataIter): # pylint: disable=R0902\n '''An iterator for single batch data to help creating device DMatrix.\n Transforming input directly to histogram with normal single batch data API\n can not access weight for sketching. So this iterator acts as a staging\n area for meta info.\n\n '''\n def __init__(self, data, label, weight, base_margin, group,\n label_lower_bound, label_upper_bound,\n feature_names, feature_types):\n self.data = data\n self.label = label\n self.weight = weight\n self.base_margin = base_margin\n self.group = group\n self.label_lower_bound = label_lower_bound\n self.label_upper_bound = label_upper_bound\n self.feature_names = feature_names\n self.feature_types = feature_types\n self.it = 0 # pylint: disable=invalid-name\n super().__init__()\n\n def next(self, input_data):\n if self.it == 1:\n return 0\n self.it += 1\n input_data(data=self.data, label=self.label,\n weight=self.weight, base_margin=self.base_margin,\n group=self.group,\n label_lower_bound=self.label_lower_bound,\n label_upper_bound=self.label_upper_bound,\n feature_names=self.feature_names,\n feature_types=self.feature_types)\n return 1\n\n def reset(self):\n self.it = 0\n\n\ndef init_device_quantile_dmatrix(\n data, missing, max_bin, threads, feature_names, feature_types, **meta):\n '''Constructor for DeviceQuantileDMatrix.'''\n if not any([_is_cudf_df(data), _is_cudf_ser(data), _is_cupy_array(data),\n _is_dlpack(data), _is_iter(data)]):\n raise TypeError(str(type(data)) +\n ' is not supported for DeviceQuantileDMatrix')\n if _is_dlpack(data):\n # We specialize for dlpack because cupy will take the memory from it so\n # it can't be transformed twice.\n data = _transform_dlpack(data)\n if _is_iter(data):\n it = data\n else:\n it = SingleBatchInternalIter(\n data, **meta, feature_names=feature_names,\n feature_types=feature_types)\n\n reset_factory = ctypes.CFUNCTYPE(None, ctypes.c_void_p)\n reset_callback = reset_factory(it.reset_wrapper)\n next_factory = ctypes.CFUNCTYPE(\n ctypes.c_int,\n ctypes.c_void_p,\n )\n next_callback = next_factory(it.next_wrapper)\n handle = ctypes.c_void_p()\n ret = _LIB.XGDeviceQuantileDMatrixCreateFromCallback(\n None,\n it.proxy.handle,\n reset_callback,\n next_callback,\n ctypes.c_float(missing),\n ctypes.c_int(threads),\n ctypes.c_int(max_bin),\n ctypes.byref(handle)\n )\n if it.exception:\n raise it.exception\n # delay check_call to throw intermediate exception first\n _check_call(ret)\n matrix = DeviceQuantileDMatrix(handle)\n feature_names = matrix.feature_names\n feature_types = matrix.feature_types\n matrix.handle = None\n return handle, feature_names, feature_types\n\n\ndef _device_quantile_transform(data, feature_names, feature_types):\n if _is_cudf_df(data):\n return _transform_cudf_df(data, feature_names, feature_types)\n if _is_cudf_ser(data):\n return _transform_cudf_df(data, feature_names, feature_types)\n if _is_cupy_array(data):\n data = _transform_cupy_array(data)\n return data, feature_names, feature_types\n if _is_dlpack(data):\n return _transform_dlpack(data), feature_names, feature_types\n raise TypeError('Value type is not supported for data iterator:' +\n str(type(data)))\n\n\ndef dispatch_device_quantile_dmatrix_set_data(proxy, data):\n '''Dispatch for DeviceQuantileDMatrix.'''\n if _is_cudf_df(data):\n proxy._set_data_from_cuda_columnar(data) # pylint: disable=W0212\n return\n if _is_cudf_ser(data):\n proxy._set_data_from_cuda_columnar(data) # pylint: disable=W0212\n return\n if _is_cupy_array(data):\n proxy._set_data_from_cuda_interface(data) # pylint: disable=W0212\n return\n if _is_dlpack(data):\n data = _transform_dlpack(data)\n proxy._set_data_from_cuda_interface(data) # pylint: disable=W0212\n return\n raise TypeError('Value type is not supported for data iterator:' +\n str(type(data)))\n" ]
[ [ "numpy.array", "numpy.isnan", "numpy.vectorize", "numpy.ascontiguousarray", "pandas.api.types.is_sparse" ] ]
xieyulai/MSP-STTN
[ "4f986b40fb0f3c292dcb6e186ed9b8aba1f7306b" ]
[ "dataset/data_fetcher_long.py" ]
[ "import numpy as np\nimport torch\nimport time\n\nfrom dataset.utils import string2timestamp\n\n\nclass DataFetcher(object):\n \"\"\"\n construct XC, XP, XT, Y\n\n current timestamp - offset = timestamp of interest\n data = fetchdata (timestamp of interest)\n \"\"\"\n\n def __init__(self, data, raw_ts, avg_data, ext_cls, len_test, t=48):\n assert len(data) == len(raw_ts)\n\n super(DataFetcher, self).__init__()\n\n self.data = data\n self.average_data = avg_data\n self.external_cls = ext_cls\n self.raw_ts = raw_ts\n self.len_test = len_test\n self.T = t\n\n # get time offset between adjacent slices\n assert (t == 24 or t == 48, 'T should be 24 / 48 or the code have to be edit')\n self.offset_frame = np.timedelta64(24 * 60 // self.T, 'm')\n self.ts = string2timestamp(self.raw_ts, self.offset_frame) # convert to timestamp\n\n # print('catch ts:\\n', self.ts[288:384]) 2013-07-07 2013-07-09\n # create index\n self.idx_of_ts = dict()\n for idx, _ts in enumerate(self.ts):\n self.idx_of_ts[_ts] = idx\n\n def dat_of_matrix(self, ts_mat):\n dat_mat = [[self.data[self.idx_of_ts[ts]] for ts in ts_seq] for ts_seq in ts_mat]\n x_c = dat_mat[0]\n x_p = dat_mat[1]\n x_t = dat_mat[2]\n\n return x_c, x_p, x_t\n\n def is_matrix_valid(self, ts_mat):\n \"\"\"\n validation for timestamp matrix\n \"\"\"\n for ts_seq in ts_mat:\n for ts in ts_seq:\n if ts not in self.idx_of_ts.keys():\n return False, ts\n return True, None\n\n def create_timestamp_matrix(self, cur_ts, offset_mat):\n \"\"\"\n get all pd_ts sequence of interest according current pd_ts and all pd_ts offset sequence\n pd_ts: pandas timestamp\n pto: pandas timestamp offset\n ptos: pandas timestamp offset sequence\n all_ptos: all pandas timestamp offset sequence from Closeness, Period and Trend\n \"\"\"\n # closeness sequence length is 4, take the first 4 interval\n # Period sequence length is 2, take the first two days\n timestamp_matrix = \\\n [\n [\n cur_ts - offset * self.offset_frame\n for offset in offset_seq\n ]\n for offset_seq in offset_mat # 双重嵌套list generator\n ]\n\n return timestamp_matrix\n\n def fetch_data(self, dconf):\n \"\"\"\n construct the array of data while doing validation\n \"\"\"\n lc = dconf.len_close # 3\n lp = dconf.len_period # 2\n lt = dconf.len_trend # 0\n fp = dconf.pad_forward_period # 0\n bp = dconf.pad_back_period # 0\n ft = dconf.pad_forward_trend # 0\n bt = dconf.pad_back_trend # 0\n ip = dconf.interval_period # 1\n it = dconf.interval_trend # 7\n print(' DataFetcher:',\n 'With Length: %d, %d, %d; ' % (lc, lp, lt),\n 'with Padding: %d %d, %d %d; ' % (fp, bp, ft, bt),\n 'with Interval: %d %d.' % (ip, it))\n r_c = range(1, lc + 1)\n rl_p = [range(ip * self.T * i - fp, ip * self.T * i + bp + 1) for i in range(1, lp + 1)]\n rl_t = [range(it * self.T * i - ft, it * self.T * i + bt + 1) for i in range(1, lt + 1)]\n\n # [[1, 2, 3, 4], [48, 96], []]\n offset_mat = \\\n [\n [e for e in r_c], # closeness\n [e for r_p in rl_p for e in r_p], # period\n [e for r_t in rl_t for e in r_t] # trend\n ]\n\n # fetching loop\n x, y, y_typ, ts_x, ts_y = [], [], [], [], []\n ts_dumped = []\n # 96\n largest_interval = max([k[-1] if len(k) is not 0 else 0 for k in offset_mat]) # init using the largest interval\n for cur_ts in self.ts[largest_interval:]:\n # cur_ts:2013-07-03T00:00\n ts_mat = self.create_timestamp_matrix(cur_ts, offset_mat) # list nest list\n\n # timestamp validation\n flag, pos = self.is_matrix_valid(ts_mat)\n if flag is False:\n ts_dumped.append((cur_ts, pos))\n continue\n\n x_c, x_p, x_t = self.dat_of_matrix(ts_mat)\n # concat as channel\n x_exist = [x_ for x_ in [x_c, x_p, x_t] if len(x_) > 0]\n x.append(np.vstack([np.stack(x_, axis=0) for x_ in x_exist]))\n y.append(self.data[self.idx_of_ts[cur_ts]])\n ext_cls = self.external_cls[self.idx_of_ts[cur_ts]]\n y_typ.append(ext_cls)\n ts_x.append(ts_mat[0] + ts_mat[1] + ts_mat[2])\n # ts_y中保存了具有完整所需信息的时间间隔\n ts_y.append(cur_ts)\n\n # concat to tensor\n x = np.asarray(x)[10:]\n y = np.asarray(y)[10:]\n y_typ = np.asarray(y_typ)[10:]\n # print(y_typ.shape)\n\n x_am = []\n for val_ts in ts_y[::self.T]:\n idx = self.idx_of_ts[val_ts]\n for i in range(self.T):\n x_am.append(self.data[idx+6:idx+10])\n x_am = np.asarray(x_am)[:-10]\n X_context = np.concatenate([x_am, x], axis=1)\n # print(X_context.shape)\n\n # INPUT\n inp = []\n for val_ts in ts_y[::self.T]:\n idx = self.idx_of_ts[val_ts]\n inp.append(self.average_data[idx:idx+self.T])\n X_input = np.vstack(inp)[10:]\n\n X_inp_q = np.vstack(inp)[10:][:, :4]\n X_input_q = np.concatenate([X_inp_q, x], axis=1)\n # print(X_input.shape)\n\n print(\" Dumped \", len(ts_dumped), \" data.\")\n return X_context, X_input, X_input_q, y, y_typ, ts_x, ts_y" ]
[ [ "numpy.concatenate", "numpy.asarray", "numpy.stack", "numpy.timedelta64", "numpy.vstack" ] ]
mrandri19/alfi
[ "3782ab93ab8d77f55914b0795db0f132088c5281" ]
[ "experiments/evaluation_scripts_for_paper/compare_p53_parameters.py" ]
[ "import argparse\nimport yaml\nimport seaborn as sns\nimport time\nimport numpy as np\nimport torch\n\nfrom matplotlib import pyplot as plt\nfrom pathlib import Path\n\nfrom alfi.datasets import P53Data\nfrom alfi.plot import tight_kwargs\n\nfrom experiments.model_specs.variational import build_variational, plot_variational\n\n\"\"\"\nThis experiment compares the parameters on which Alfi converges with those the original Barenco paper found.\n\"\"\"\n# ------Config------ #\n\nwith open(\"experiments/experiments.yaml\", 'r') as stream:\n try:\n config = yaml.safe_load(stream)\n except yaml.YAMLError as exc:\n print(exc)\n exit()\n\ndataset_choices = list(config.keys())\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--samples', type=int, default=5)\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n data_config = config['p53']\n experiments = data_config['experiments']\n for experiment in experiments:\n if experiment['method'] == 'variational':\n break\n\n print(experiment)\n method = experiment['method']\n\n # Create experiments path\n filepath = Path('experiments', 'p53', method)\n filepath.mkdir(parents=True, exist_ok=True)\n\n kinetics_samples = list()\n for i in range(args.samples):\n dataset = P53Data(replicate=0, data_dir='data')\n\n # Construct model\n modelparams = experiment['model-params'] if 'model-params' in experiment else None\n model, trainer, plotter = build_variational(\n dataset, modelparams, checkpoint_dir=None)\n\n trainer.train(**experiment['train_params'], step_size=5e-1)\n\n kinetics = np.array(\n [x.detach().squeeze().numpy() for x in [model.basal_rate, model.sensitivity, model.decay_rate]])\n\n kinetics_samples.append(kinetics)\n\n samples = np.stack(kinetics_samples)\n print(samples.shape)\n kinetics = samples.mean(0)\n err = samples.std(0)\n print(kinetics.shape, err.shape)\n labels = ['Basal rates', 'Sensitivities', 'Decay rates']\n\n plotter.plot_double_bar(kinetics, labels, params_var=err, ground_truths=P53Data.params_ground_truth(),\n figsize=(6.5, 2.3),\n yticks=[\n np.linspace(0, 0.12, 5),\n np.linspace(0, 1.2, 4),\n np.arange(0, 1.1, 0.2),\n ])\n plt.tight_layout()\n\n plt.savefig(filepath / 'linear-kinetics2.pdf', **tight_kwargs)\n" ]
[ [ "matplotlib.pyplot.savefig", "numpy.stack", "numpy.arange", "matplotlib.pyplot.tight_layout", "numpy.linspace" ] ]
AakashSudhakar/biodata-compound-activity-with-bioassays
[ "a56fe46e753eeaf05f1419b2ec501881362268c3" ]
[ "structures/dataset_preprocessor.py" ]
[ "#!python3\n\n\nimport pandas as pd\nfrom os import listdir\nfrom os.path import isfile, join\n\n\nclass Dataset_Preprocessor(object):\n \"\"\" Class object instance for bioassay dataset preprocessing analysis. \"\"\"\n def __init__(self):\n \"\"\" Initializer method. \"\"\"\n self.REL_PATH_TO_DATA = \"../datasets/external/bioassay-datasets/\"\n \n def load_data(self, which=\"all\", delimiter=\"_\"):\n \"\"\" \n Instance method that conditionally loads in directed datasets into tree-based dictionary hierarchy. \n \n INPUTS: \n {which}:\n - str(train): Read in training dataset(s).\n - str(test): Read in testing dataset(s).\n - str(full): Read in concatenated training and testing dataset(s).\n - str(all): Read in all three (training, testing, full) dataset(s) separated by sublevel keys. (DEFAULT)\n {delimiter}:\n - str(_): Sets dataset filename delimiter as underscore symbol. (DEFAULT)\n \n OUTPUTS:\n dict: Tree-based dictionary with key-value pairs of bioassay IDs and their associated datasets (pd.DataFrame).\n \"\"\"\n # Validate conditional data loading arguments\n if which not in [\"all\", \"both\", \"train\", \"test\"]:\n raise ValueError(\"ERROR: Inappropriate value passed to argument `which`.\\n\\nExpected value in range:\\n - all\\n - both\\n - train\\n - test\\n\\nActual:\\n - {}\".format(which))\n \n if which in [\"train\", \"test\", \"full\"]:\n raise NotImplementedError(\"ERROR: Value passed to argument is currently not implemented and does not function. Please try again later or alter your keyword argument value submission.\")\n \n # Validate data delimiting arguments\n if type(delimiter) is not str:\n raise ValueError(\"ERROR: Inappropriate data type passed to argument `delimiter`.\\n\\nExpected type(s):\\n - [str]\\n\\nActual:\\n - [{}]\".format(str(type(delimiter))))\n \n FILENAMES = list()\n for file in listdir(self.REL_PATH_TO_DATA):\n filename = file.split(delimiter)[0]\n if isfile(join(self.REL_PATH_TO_DATA, file)) and filename not in FILENAMES:\n FILENAMES.append(filename)\n \n if which == \"all\":\n DATASETS = dict.fromkeys(FILENAMES,\n dict.fromkeys([\"train\", \"test\", \"full\"]))\n for filename in FILENAMES:\n files = [file for file in listdir(self.REL_PATH_TO_DATA) if file.startswith(filename)]\n if files[0].endswith(\"train.csv\"):\n train_data, test_data = files[0], files[1]\n elif files[0].endswith(\"test.csv\"):\n train_data, test_data = files[1], files[0]\n \n DATASETS[filename][\"train\"] = pd.read_csv(self.REL_PATH_TO_DATA + train_data)\n DATASETS[filename][\"test\"] = pd.read_csv(self.REL_PATH_TO_DATA + test_data)\n DATASETS[filename][\"full\"] = pd.concat([DATASETS[filename][\"train\"], DATASETS[filename][\"test\"]], \n keys=[\"train\", \"test\"])\n return DATASETS\n \n def encode_feature(self, dataset_structure, old_feature, new_feature, encoding_map):\n \"\"\" \n Instance method that encodes data from all datasets to new features using a map structure.\n \n INPUTS:\n {dataset_structure}:\n - dict: Input tree-based dictionary structure containing datasets to iterate over for feature encoding. \n {old_feature}:\n - str: Name of original feature across all input datasets over which to encode.\n {new_feature}:\n - str: Name of new feature to generate across all input datasets.\n {encoding_map}:\n - dict: Accumulation of key-value pairs, where occurrences of keys are replaced with values across observed feature.\n \n OUTPUTS:\n NoneType: Iterative in-place data encoding does not return any new object(s).\n \"\"\"\n for key, value in dataset_structure.items():\n if isinstance(value, dict):\n self.encode_feature(value, old_feature, new_feature, encoding_map)\n else:\n value[new_feature] = value[old_feature].map(encoding_map)" ]
[ [ "pandas.read_csv", "pandas.concat" ] ]
siddharthbharthulwar/Synthetic-Vision-System
[ "b6cbfdcd474639538f0d60eb4ba1d45a7fec0b44" ]
[ "Pipeline/testing.py" ]
[ "from terraingrid import TerrainGrid\nimport matplotlib.pyplot as plt \nfrom sklearn.metrics import f1_score, precision_score, recall_score\nimport numpy as np \nimport cv2 as cv\ndef pixel_accuracy(eval_segm, gt_segm):\n '''\n sum_i(n_ii) / sum_i(t_i)\n '''\n\n check_size(eval_segm, gt_segm)\n\n cl, n_cl = extract_classes(gt_segm)\n eval_mask, gt_mask = extract_both_masks(eval_segm, gt_segm, cl, n_cl)\n\n sum_n_ii = 0\n sum_t_i = 0\n\n for i, c in enumerate(cl):\n curr_eval_mask = eval_mask[i, :, :]\n curr_gt_mask = gt_mask[i, :, :]\n\n sum_n_ii += np.sum(np.logical_and(curr_eval_mask, curr_gt_mask))\n sum_t_i += np.sum(curr_gt_mask)\n \n if (sum_t_i == 0):\n pixel_accuracy_ = 0\n else:\n pixel_accuracy_ = sum_n_ii / sum_t_i\n\n return pixel_accuracy_\n\ndef mean_accuracy(eval_segm, gt_segm):\n '''\n (1/n_cl) sum_i(n_ii/t_i)\n '''\n\n check_size(eval_segm, gt_segm)\n\n cl, n_cl = extract_classes(gt_segm)\n eval_mask, gt_mask = extract_both_masks(eval_segm, gt_segm, cl, n_cl)\n\n accuracy = list([0]) * n_cl\n\n for i, c in enumerate(cl):\n curr_eval_mask = eval_mask[i, :, :]\n curr_gt_mask = gt_mask[i, :, :]\n\n n_ii = np.sum(np.logical_and(curr_eval_mask, curr_gt_mask))\n t_i = np.sum(curr_gt_mask)\n \n if (t_i != 0):\n accuracy[i] = n_ii / t_i\n\n mean_accuracy_ = np.mean(accuracy)\n return mean_accuracy_\n\ndef mean_IU(eval_segm, gt_segm):\n '''\n (1/n_cl) * sum_i(n_ii / (t_i + sum_j(n_ji) - n_ii))\n '''\n\n check_size(eval_segm, gt_segm)\n\n cl, n_cl = union_classes(eval_segm, gt_segm)\n _, n_cl_gt = extract_classes(gt_segm)\n eval_mask, gt_mask = extract_both_masks(eval_segm, gt_segm, cl, n_cl)\n\n IU = list([0]) * n_cl\n\n for i, c in enumerate(cl):\n curr_eval_mask = eval_mask[i, :, :]\n curr_gt_mask = gt_mask[i, :, :]\n \n if (np.sum(curr_eval_mask) == 0) or (np.sum(curr_gt_mask) == 0):\n continue\n\n n_ii = np.sum(np.logical_and(curr_eval_mask, curr_gt_mask))\n t_i = np.sum(curr_gt_mask)\n n_ij = np.sum(curr_eval_mask)\n\n IU[i] = n_ii / (t_i + n_ij - n_ii)\n \n mean_IU_ = np.sum(IU) / n_cl_gt\n return mean_IU_\n\ndef frequency_weighted_IU(eval_segm, gt_segm):\n '''\n sum_k(t_k)^(-1) * sum_i((t_i*n_ii)/(t_i + sum_j(n_ji) - n_ii))\n '''\n\n check_size(eval_segm, gt_segm)\n\n cl, n_cl = union_classes(eval_segm, gt_segm)\n eval_mask, gt_mask = extract_both_masks(eval_segm, gt_segm, cl, n_cl)\n\n frequency_weighted_IU_ = list([0]) * n_cl\n\n for i, c in enumerate(cl):\n curr_eval_mask = eval_mask[i, :, :]\n curr_gt_mask = gt_mask[i, :, :]\n \n if (np.sum(curr_eval_mask) == 0) or (np.sum(curr_gt_mask) == 0):\n continue\n\n n_ii = np.sum(np.logical_and(curr_eval_mask, curr_gt_mask))\n t_i = np.sum(curr_gt_mask)\n n_ij = np.sum(curr_eval_mask)\n\n frequency_weighted_IU_[i] = (t_i * n_ii) / (t_i + n_ij - n_ii)\n \n sum_k_t_k = get_pixel_area(eval_segm)\n \n frequency_weighted_IU_ = np.sum(frequency_weighted_IU_) / sum_k_t_k\n return frequency_weighted_IU_\n\n'''\nAuxiliary functions used during evaluation.\n'''\ndef get_pixel_area(segm):\n return segm.shape[0] * segm.shape[1]\n\ndef extract_both_masks(eval_segm, gt_segm, cl, n_cl):\n eval_mask = extract_masks(eval_segm, cl, n_cl)\n gt_mask = extract_masks(gt_segm, cl, n_cl)\n\n return eval_mask, gt_mask\n\ndef extract_classes(segm):\n cl = np.unique(segm)\n n_cl = len(cl)\n\n return cl, n_cl\n\ndef union_classes(eval_segm, gt_segm):\n eval_cl, _ = extract_classes(eval_segm)\n gt_cl, _ = extract_classes(gt_segm)\n\n cl = np.union1d(eval_cl, gt_cl)\n n_cl = len(cl)\n\n return cl, n_cl\n\ndef extract_masks(segm, cl, n_cl):\n h, w = segm_size(segm)\n masks = np.zeros((n_cl, h, w))\n\n for i, c in enumerate(cl):\n masks[i, :, :] = segm == c\n\n return masks\n\ndef segm_size(segm):\n try:\n height = segm.shape[0]\n width = segm.shape[1]\n except IndexError:\n raise\n\n return height, width\n\ndef check_size(eval_segm, gt_segm):\n h_e, w_e = segm_size(eval_segm)\n h_g, w_g = segm_size(gt_segm)\n\n if (h_e != h_g) or (w_e != w_g):\n raise EvalSegErr(\"DiffDim: Different dimensions of matrices!\")\n\n'''\nExceptions\n'''\nclass EvalSegErr(Exception):\n def __init__(self, value):\n self.value = value\n\n def __str__(self):\n return repr(self.value)\n\n\nDSM9 = \"D:\\\\Documents\\\\School\\\\2019-20\\\\ISEF 2020\\\\AHN\\\\R5_37FZ2\\\\r5_37fz2.tif\"\nDSM6 = \"D:\\\\Documents\\\\School\\\\2019-20\\\\ISEF 2020\\\\AHN\\\\R5_37FN2\\\\r5_37fn2.tif\"\nDSM8 = \"D:\\\\Documents\\\\School\\\\2019-20\\\\ISEF 2020\\\\AHN\\\\R5_37FZ1\\\\r5_37fz1.tif\"\nDSM7 = \"D:\\\\Documents\\\\School\\\\2019-20\\\\ISEF 2020\\\\AHN\\\\R5_37EZ2\\\\r5_37ez2.tif\"\nDSM4 = \"D:\\\\Documents\\\\School\\\\2019-20\\\\ISEF 2020\\\\AHN\\\\R5_37EN2\\\\r5_37en2.tif\"\nDSM5 = \"D:\\\\Documents\\\\School\\\\2019-20\\\\ISEF 2020\\\\AHN\\\\R5_37FN1\\\\r5_37fn1.tif\"\n\n\n\nr0 = r\"D:\\Documents\\School\\2019-20\\ISEF 2020\\HighProcessed\\r_37ez2.tif\"\nr1 = r\"D:\\Documents\\School\\2019-20\\ISEF 2020\\HighProcessed\\r_37fz1.tif\"\n\n\nbuildings = r\"D:\\Documents\\School\\2019-20\\ISEF 2020\\TRUTHS\\buildings.png\"\nvegetation = r\"D:\\Documents\\School\\2019-20\\ISEF 2020\\TRUTHS\\trees.png\"\n\n\n\na = TerrainGrid((r0), (1,1), 1)\na.arrayValues = a.arrayValues[8600:10200, 7600:9200]\n\n\n\nbuildings_true = cv.imread(buildings, cv.IMREAD_GRAYSCALE).astype('uint8')[8600:10200, 7600:9200]\nvegetation_true = cv.imread(vegetation, cv.IMREAD_GRAYSCALE).astype('uint8')[8600:10200, 7600:9200]\n#bldval = 144, vegval = 116\n\n\ntrue_output = (buildings_true).astype('uint8')\n\nx = []\ny = []\nstart = 0\nwhile (start < 6):\n\n a.classification(3, 2, 1, 4, 600, start, 144, 116, False)\n x.append(start)\n predicted_output = (a.labeled_buildings).astype('uint8')\n y.append((pixel_accuracy(predicted_output, true_output)) * 100)\n start += 0.01\n\nfig, ax = plt.subplots()\nax.plot(x, y)\n\nax.set(xlabel='standard deviation threshold(σ)', ylabel='accuracy (%)',\n title='Accuracy of Labelling (%) vs Standard Deviation Threshold')\nax.grid()\n\nplt.show()" ]
[ [ "numpy.union1d", "numpy.zeros", "numpy.sum", "numpy.mean", "matplotlib.pyplot.subplots", "numpy.logical_and", "matplotlib.pyplot.show", "numpy.unique" ] ]
erinaceous/shadows
[ "43c86c18936f6af4c0c54f30419e8f7bfb244e9a" ]
[ "learning/edges/extractor/utils.py" ]
[ "#!/usr/bin/env python\n# vim: set tabstop=4 shiftwidth=4 textwidth=79 cc=72,79:\n\"\"\"\n feature_utils: Utilities relating to extract_features.py\n Original Author: Owain Jones [[email protected]]\n\"\"\"\n\nfrom __future__ import print_function\nimport numpy as np\nimport random\nimport gzip\nimport math\nimport cv2\n\n\n# Configurable defaults\nNORMAL_LENGTH = 30\nCLASSES = ['shadow', 'penumbra', 'object']\nPN_RATIO = 3 # positive/negative example ratio to enforce\nDISTANCE = 3 # minimum pixel distance between contour points\nLENGTH = 30 # default length of normals\n\n\n# Possible names for channels within the HSV/BGR colour spaces.\n# mat[:, :, CHANNELS['r']] would get you mat[:, :, 2] -- a 2D array of\n# the red channel from the BGR image, mat.\nCHANNELS = {\n 'h': 0,\n 'hue': 0,\n 's': 1,\n 'sat': 1,\n 'saturation': 1,\n 'v': 2,\n 'val': 2,\n 'value': 2,\n 'r': 2,\n 'red': 2,\n 'g': 1,\n 'green': 1,\n 'b': 0,\n 'blue': 0\n}\n\n\ndef load_image(path, blur=0, bifilter=0):\n \"\"\"Loads an image at `path` and also converts it to the HSV colour\n space. Also optionally performs Gaussian blur and Bilateral\n filtering on the input image.\n\n Returns: two image matrices; one for the original BGR image, and\n one for the image converted to the HSV colour space.\n \"\"\"\n image = cv2.imread(path, cv2.CV_LOAD_IMAGE_COLOR)\n if bifilter > 0:\n image = cv2.bilateralFilter(image, -1, bifilter, bifilter)\n if blur > 0:\n image = cv2.GaussianBlur(image, (blur, blur), 0)\n image_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n return (image, image_hsv)\n\n\ndef load_ground_truth(path, penumbra_as_shadow=False):\n \"\"\"Loads a ground truth image (as a 1-channel grayscale image) and\n extracts the shadow, penumbra and object masks from it.\n\n Returns: A tuple of 3 image matrices:\n (shadow, penumbra, object)\n \"\"\"\n image = cv2.imread(path, cv2.CV_LOAD_IMAGE_GRAYSCALE)\n shadows = image.copy()\n if penumbra_as_shadow:\n shadows[shadows == 25] = 0\n else:\n shadows[shadows == 25] = 255\n shadows[shadows == 153] = 255\n shadows[shadows < 255] = 0\n penumbra = image.copy()\n if penumbra_as_shadow:\n penumbra.fill(255)\n else:\n penumbra[penumbra != 25] = 255\n penumbra[penumbra == 25] = 0\n objects = image.copy()\n objects[objects != 153] = 255\n objects[objects == 153] = 0\n return (shadows, penumbra, objects)\n\n\ndef get_normal(line, length=0):\n \"\"\"Gets the normal of a line (flips it 90 degrees).\n Line is a pair of tuples -- ((x, y), (x, y)) -- representing the\n two ends of the line.\n\n If length is set to a value > 0, the normal is also set to that\n fixed length.\n \"\"\"\n if type(line) not in [list, tuple]:\n line = (\n line[0][0], line[1][0] \n )\n\n if length <= 0:\n return (\n (line[1][0], line[0][1]),\n (line[0][0], line[1][1])\n )\n half_length = length / 2\n center = (\n line[0][0] + ((line[1][0] - line[0][0]) / 2),\n line[0][1] + ((line[1][1] - line[0][1]) / 2)\n )\n diff = (\n line[1][0] - line[0][0],\n line[1][1] - line[0][1]\n )\n angle = math.degrees(math.atan2(diff[0], diff[1]))\n return (\n (center[0] - half_length * math.sin(angle),\n center[1] - half_length * math.cos(angle)),\n (center[0] + half_length * math.sin(angle),\n center[1] + half_length * math.cos(angle))\n )\n\n\ndef round_partial(value, resolution):\n \"\"\"Rounds a number to a partial interval. Good for rounding things\n up/down to the nearest value of 5 for example.\n\n Thanks to http://stackoverflow.com/a/8118808 for this neat trick\n \"\"\"\n return round(value / resolution) * resolution\n\n\ndef anyrange(start, stop, interval, **kwargs):\n \"\"\"Smarter version of range() -- if the start number > end number,\n inverts interval (subtracts from stop until start is reached).\n \"\"\"\n if start > stop:\n return np.arange(start, stop, -interval, **kwargs)\n return np.arange(start, stop, interval, **kwargs)\n\n\ndef quantize_contour(contour, bin_size=4):\n \"\"\"Reduces the resolution (number of points) of a contour by\n treating the image as a grid with square cells of `bin_size`\n pixels width and height. Any point within the square has its\n coordinates set to the center of the square, and only one point\n is stored per square.\n If a line in the contour spans more than one square, a point is\n added for each square it touches.\n This is a simple way of reducing the number of segments in a\n contour, and allows for uniform distribution of normals across\n a contour (to prevent bias when sampling features from a contour)\n\n Returns: A quantized version of the contour.\n \"\"\"\n if bin_size <= 1:\n center = bin_size\n else:\n center = bin_size / 2\n bins = []\n idx = 0\n for segment in contour:\n segment = segment.flatten()\n x, y = (\n round_partial(segment[0], center),\n round_partial(segment[1], center)\n )\n if (x, y) not in bins:\n # TODO: Figure out how to get a uniform distribution of\n # points across straight lines (interpolation?)\n # idx = len(bins) - 1\n # if idx > 0:\n # lastx, lasty = bins[idx - 1]\n # midx = anyrange(x, lastx, bin_size)\n # midy = anyrange(y, lasty, bin_size)\n # print(midx, midy)\n bins.append((x, y))\n return bins\n\n\ndef get_distance(point1, point2):\n \"\"\"Calculate the distance between two aribtrary points.\"\"\"\n try:\n d = math.sqrt((abs(point2[0] - point1[0]) ^ 2) +\n (abs(point2[1] - point1[1]) ^ 2))\n except ValueError:\n d = 0.0\n return d\n\n\ndef minimum_distance_contour(contour, distance=0):\n \"\"\"Reduce the number of points in a contour by enforcing a minimum\n pixel distance between points.\n\n Returns: A similar contour (same structure) but with (hopefully)\n less points.\n \"\"\"\n new_contour = list()\n last_point = contour[0]\n for p_idx, point in enumerate(contour):\n if p_idx == 0:\n continue\n if get_distance(last_point, point) > distance:\n new_contour.append(point)\n last_point = point\n\n return new_contour\n\n\ndef get_normals(contours, length=40, epsilon=0, array=None):\n \"\"\"Loops over a list of lists [of lists] of contour points -- like\n the lists generated by cv2.findContours().\n\n Returns a list of list of lists:\n [contours -> [contour -> [line segment normal (x, y)]]]\n \"\"\"\n new_contours = list()\n for c_idx, contour in enumerate(contours):\n new_contour = list()\n for s_idx, segment in enumerate(contour):\n\n # Skip the first point\n if s_idx == 0:\n continue\n\n # Get the current point and the previous point in the list\n # to make up our line.\n point1 = contour[s_idx - 1]\n point2 = contour[s_idx]\n normal = get_normal((point1, point2), length=length)\n new_contour.append(normal)\n new_contours.append(new_contour)\n return new_contours\n\n\ndef get_values(array, line):\n \"\"\"Get values across a line in a 2D array.\n Lines can be at any angle. The resulting values will be\n interpolated if the line crosses multiple pixels at each point.\n Lines at the edges of the array are clipped to remain inside the\n array.\n\n Returns: a 1D array of values.\n \"\"\"\n x1, y1 = line[0]\n x2, y2 = line[1]\n length = np.hypot(x2 - x1, y2 - y1)\n x = np.clip(np.linspace(x1, y2, length), 0, array.shape[0] - 1)\n y = np.clip(np.linspace(y1, y2, length), 0, array.shape[1] - 1)\n values = []\n for i in range(int(length)):\n values.append(array[x[i], y[i]])\n return np.array(values)\n\n\n\ndef get_edges(image):\n \"\"\"Do edge detection on a multi-channel image.\n\n Returns: An image with the same number of channels as the input\n image, with Canny edge detection done on each channel.\n \"\"\"\n # output = image.copy()\n # channels = image.shape[2]\n # for channel in range(0, channels):\n # output[:, :, channel] = cv2.Canny(image[:, :, channel], 0, 1)\n\n # Take the Lalonde et. al. approach to detecting edges -- get gradient\n # magnitudes, apply watershed on the gradient map, and filter out weak\n # edges using a Canny detector.\n\n # Smooth out noise! 33 is the magic number\n # new = cv2.bilateralFilter(image, 66, 66, 66)\n new = image.copy()\n\n Sx = cv2.Sobel(new, cv2.CV_32F, 1, 0, ksize=3)\n Sy = cv2.Sobel(new, cv2.CV_32F, 0, 1, ksize=3)\n mag = np.uint8(cv2.magnitude(Sx, Sy))\n grey = np.int32(cv2.cvtColor(mag, cv2.COLOR_BGR2GRAY))\n cv2.watershed(mag, grey)\n mag_grey = cv2.cvtColor(mag, cv2.COLOR_BGR2GRAY)\n _, mag_edges = cv2.threshold(mag_grey, 0, 255,\n cv2.THRESH_OTSU | cv2.THRESH_BINARY)\n\n # Lalonde paper says they used an upper threshold, empirically derived,\n # of 0.3. Their code had floating point images in the range 0..1, so\n # convert that to 8 bit (0..255)\n mag_edges = cv2.Canny(mag_edges, 0, 255 * 0.3)\n\n #element = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))\n #mag_edges = cv2.dilate(mag_edges, element)\n #mag_edges = cv2.GaussianBlur(mag_edges, (9, 9), 0)\n #mag_edges[mag_edges < 150] = 0\n #mag_edges[mag_edges >= 150] = 255\n\n return mag_edges\n\n\ndef flatten_sv_edges(image):\n \"\"\"Flatten a Hue/Sat/Value edge image into a single channel. Edge\n pixels present in both the saturation and value channels are\n kept.\n \"\"\"\n output = image[:, :, 0].copy()\n output.fill(0)\n output = image[:, :, 1] & image[:, :, 2]\n return output\n\n\ndef flatten_edges(image):\n \"\"\"Flatten an image into a single channel. Simply converts it to\n grayscale and thresholds so that anything > 0 == 255.\n \"\"\"\n output = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n output[output > 0] = 255\n return output\n\n\ndef get_contours(edges):\n \"\"\"Get the contours of the edges in an image. Uses\n cv2.findContours() internally.\n\n OpenCV's contours lists are a little weird\n (contours -> [contour -> [[segment]]]) -- the segments\n (x, y points) are kept in an array of size 1 which doesn't need\n to be there and isn't an intuitive thing to use. Get odd numpy\n errors.\n\n So this function also converts the data to the following structure:\n list of contours -> [\n list of contour segments -> [\n segment (x, y point)\n ]\n ]\n\n Returns: A list of contours.\n \"\"\"\n contours, _ = cv2.findContours(edges.copy(), cv2.RETR_LIST,\n cv2.CHAIN_APPROX_SIMPLE)\n new_contours = []\n for contour in contours:\n new_contour = []\n for segment in contour:\n new_contour.append(segment.flatten())\n new_contours.append(new_contour)\n return new_contours\n\n\ndef olbp(array, point):\n \"\"\"Perform simple local binary pattern calculation with a fixed\n 3x3 neighbourhood. Thanks to:\n http://www.bytefish.de/blog/local_binary_patterns/\n for a really nice explanation of LBP.\n\n Won't return correct results around the image boundaries.\n Because it's only a 3x3 neighbourhood, probably very susceptible\n to noise.\n TODO: Bigger neighbourhood. Variable size maybe?\n\n Returns: A single decimal number (the encoded pattern)\n \"\"\"\n x, y = point\n\n # Make sure we're within the array bounds.\n if x < 1:\n x = 1\n if x > (array.shape[0] - 2):\n x = array.shape[0] - 2\n if y < 1:\n y = 1\n if y > (array.shape[1] - 2):\n y = array.shape[1] - 2\n\n center = array[x, y]\n code = 0\n code |= (array[x - 1, y - 1] > center) << 7\n code |= (array[x - 1, y] > center) << 6\n code |= (array[x - 1, y + 1] > center) << 5\n code |= (array[x, y - 1] > center) << 4\n code |= (array[x, y + 1] > center) << 3\n code |= (array[x + 1, y - 1] > center) << 2\n code |= (array[x + 1, y] > center) << 1\n code |= (array[x + 1, y + 1] > center) << 0\n return code\n\n\ndef flip_point(point, array):\n \"\"\"Flip a point so that X=>Y and Y=>X. Also clip its values so that\n they fit within an array.\n\n Returns: The same point, but fixed.\n\n (OpenCV arrays in numpy go row => column, or y => x, which\n confuses me as I'm used to thinking of images in (x, y)\n coordinates.)\n \"\"\"\n return (\n np.clip(point[1], 0, array.shape[0] - 1),\n np.clip(point[0], 0, array.shape[1] - 1)\n )\n\n\ndef get_point_class(line, ground_truth):\n \"\"\"Finds the label class of a line in an array, based\n on the ground truth masks.\n\n Picks the class which has the maximum number of instances across\n the line.\n\n Returns: A string, indicating the class label.\n (e.g. 'background' or 'shadow')\n \"\"\"\n x1, y1 = line[0]\n x2, y2 = line[1]\n centerx = x1 + ((x2 - x1) / 2.0)\n centery = y1 + ((y2 - y1) / 2.0)\n\n labels = {'background': -1, 'shadow': 0, 'penumbra': 0, 'object': 0}\n for i, name in enumerate(['shadow', 'penumbra', 'object']):\n labels['background'] += 1\n if ground_truth[i][x1, y1] == 0:\n labels[name] += 1\n labels['background'] -= 1\n if ground_truth[i][x2, y2] == 0:\n labels[name] += 1\n labels['background'] -= 1\n if ground_truth[i][centerx, centery] == 0:\n labels[name] += 1\n labels['background'] -= 1\n\n v = labels.values()\n k = labels.keys()\n return k[v.index(max(v))]\n\n\ndef yesno(value):\n \"\"\"Convert 0/1 or True/False to 'yes'/'no' strings.\n Weka/LibSVM doesn't like labels that are numbers, so this is\n helpful for that.\n \"\"\"\n if value == 1 or value == True:\n return 'yes'\n return 'no'\n\n\ndef _str(value):\n \"\"\"Converts numbers to strings, rounding them to 3 decimal places.\n Converts instances of NaN (Not a Number), or infinity, to '0'.\n \"\"\"\n if value in (np.nan, np.inf, -np.inf):\n return '0'\n if isinstance(value, float):\n return str(round(value, 3))\n return str(value)\n\n\ndef save_features_to_file(filename, features, header=False, ratio=PN_RATIO):\n \"\"\"Dump features to a CSV file. If the filename ends with .gz, save\n it to a gzipped file automatically.\n\n If ratio > 0, try and keep this ratio of negative examples to\n positive examples. If ratio > 0, the data rows are shuffled\n randomly to get an unbiased selection of negative examples.\n \"\"\"\n keys = list(features.keys())\n values = list(features.values())\n label_class_idx = keys.index('label_class')\n if ratio > 0:\n for column in values:\n random.shuffle(column)\n\n if header is True:\n mode = 'w+'\n else:\n mode = 'a+'\n\n if filename.endswith('.gz'):\n output = gzip.open(filename, mode)\n else:\n output = open(filename, mode)\n\n if header is True:\n print(','.join(keys), file=output)\n\n background = 0.0\n labelled_data = 0.0\n for i in range(0, len(values[0])):\n should_print = True\n if ratio > 0:\n example_class = values[label_class_idx][i]\n if example_class == 'background':\n try:\n cur_ratio = background / labelled_data\n except ZeroDivisionError:\n cur_ratio = ratio\n if cur_ratio < ratio:\n should_print = True\n background += 1\n else:\n should_print = False\n else:\n should_print = True\n labelled_data += 1\n if should_print:\n print(','.join([_str(column[i]) for column in values]),\n file=output)\n" ]
[ [ "numpy.array", "numpy.arange", "numpy.hypot", "numpy.clip", "numpy.linspace" ] ]
ShahroozFaghihRoohi/Phase2_Submission_Python_02
[ "896549fbbf8d6b66fc0627fe146cb2ea17701df4" ]
[ "get_sepsis_score.py" ]
[ "#!/usr/bin/env python\n\nimport numpy as np\nimport pickle\n\ndef Interpolation(InMat):\n OutMat = np.zeros(InMat.shape, dtype=float)\n for i in range(InMat.shape[1]):\n Col = InMat[:,i]\n if (np.any(np.isnan(Col))):\n if (np.all(np.isnan(Col))):\n dd = 1\n else:\n # set all first nan values to the first non-nan value\n j = 0\n while (np.isnan(Col[j]) & (j<len(Col))):\n j += 1\n Col[:j] = Col[j]\n \n # set all last nan values to the last non-nan value\n j = -1\n while (np.isnan(Col[j])) & (j>-len(Col)):\n j -= 1\n Col[j:] = Col[j]\n \n # interpolate the other nan values\n if (np.any(np.isnan(Col))):\n t = np.array(range(len(Col)))\n NonNanCol = Col[~np.isnan(Col)]\n NonNant = t[~np.isnan(Col)]\n Nant = t[np.isnan(Col)]\n \n NanColInterp = np.interp(Nant, NonNant, NonNanCol)\n Col[Nant] = NanColInterp\n OutMat[:,i] = Col\n else:\n OutMat[:,i] = Col\n \n return OutMat\n\ndef get_sepsis_score(data, model, cols, Dmean, Dstd):\n \n D = np.empty(1, dtype=object)\n \n dNormalOrig = data[:,cols]\n \n dNormal = Interpolation(dNormalOrig)\n \n DmeanMat = np.repeat(Dmean,len(dNormal),axis=0)\n DstdMat = np.repeat(Dstd,len(dNormal),axis=0)\n dNormal = np.nan_to_num((dNormal - DmeanMat) / DstdMat) \n \n D[0] = dNormal \n score = 0.5\n labelVec = model.predict(D)\n label = labelVec[0][-1]\n if (label == 2):\n label = 1\n return score, label\n\ndef load_sepsis_model():\n ModelFileName = 'ChainCRF_Model.pkl'\n with open(ModelFileName, 'rb') as file:\n ssvm, cols, Dmean, Dstd = pickle.load(file)\n\n return ssvm, cols, Dmean, Dstd \n" ]
[ [ "numpy.isnan", "numpy.nan_to_num", "numpy.empty", "numpy.zeros", "numpy.interp" ] ]
MohamedHmini/IWW
[ "b270534a2b22d45d4ad989d5402b0dea73d169ea" ]
[ "iww/features_extraction/lists_detector.py" ]
[ "import sys\nimport os\nimport pandas as pd\nimport numpy as np\nimport itertools\nfrom sklearn.manifold import TSNE\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.metrics.pairwise import euclidean_distances\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\npd.set_option('display.max_columns', 500)\npd.set_option('display.max_rows', 100)\n\n\n#sys.path.append(os.path.realpath(os.path.abspath('../')))\n\nfrom iww.features_extraction.cetd import CETD\nfrom iww.features_extraction.main_content_detector import MCD\nfrom iww.utils.dom_mapper import DOM_Mapper\nimport iww.utils.pairwise as pw\n\n\n\n\n\nclass Lists_Detector(DOM_Mapper):\n \n def __init__(self):\n \n# self.expected_vect = [1,1,1,1,1,1,1,1,1]\n \n pass\n \n \n def apply(self, \n node, \n coherence_threshold = (0.95,1), \n sub_tags_threshold = 2, \n mode = \"full\"):\n \n self.coherence_threshold = coherence_threshold\n self.sub_tags_threshold = sub_tags_threshold\n \n cetd = CETD()\n cetd.apply(self.DOM)\n\n self.absolute(node)\n self.relative(node)\n self.adjust(node)\n \n features = [\n 'xpath','LISTS.adjust.width', 'LISTS.adjust.height', 'LISTS.adjust.area', \n 'LISTS.adjust.font-size', 'LISTS.adjust.font-family', 'LISTS.adjust.background-color', \n 'LISTS.adjust.color', 'LISTS.adjust.bag-of-classes-coherence', 'LISTS.adjust.bag-of-tags-coherence',\n 'LISTS.adjust.tagsCount']\n \n self.expected_vect = np.full(len(features)-1,1)\n \n arr = self.flatten(node, features = features)\n self.xpaths = arr[:,0]\n self.X= arr[:,1:]\n \n self.get_final_results(self.xpaths, self.X)\n self.mark_results(node)\n \n pass\n \n \n \n def get_main_list(self, node, min_ratio_threshold = 0.0, nbr_nodes_threshold = 1):\n \n mcd = MCD() \n \n pass\n \n \n \n def original(self):\n \n self.map(self.DOM, fun1 = self.__init_original)\n \n pass\n \n \n def __init_original(self, node):\n \n node['bounds']['centerX'] = node['bounds']['width']/2\n node['bounds']['centerY'] = node['bounds']['height']/2\n \n return node\n \n pass\n \n \n \n def absolute(self, node):\n \n self.map(\n node, \n fun1 = self.__init_absolute, \n fun3 = self.__absolute, \n fun4 = self.__end_absolute\n )\n \n pass\n \n \n def __init_absolute(self, node):\n \n node['LISTS'] = {}\n node['LISTS']['absolute'] = {}\n node['LISTS']['absolute']['width'] = node['bounds']['width']\n node['LISTS']['absolute']['height'] = node['bounds']['height']\n node['LISTS']['absolute']['area'] = node['bounds']['width']*node['bounds']['height']\n \n node['LISTS']['absolute']['font-size'] = {node['style']['font-size']:1}\n node['LISTS']['absolute']['font-family'] = {node['style']['font-family'].lower():1}\n node['LISTS']['absolute']['color'] = {node['style']['color']:1}\n node['LISTS']['absolute']['background-color'] = {node['style']['background-color']:1}\n node['LISTS']['absolute']['bag-of-classes'] = { c: 1 for c in node['atts']['class'] } if 'class' in node['atts'].keys() else {}\n node['LISTS']['absolute']['bag-of-tags'] = {node['tagName']:1}\n \n \n return node\n \n pass\n \n \n def mergeDicts(self, parent, child):\n \n parent = dict([\n (pi, pv+child[pi]) if pi in child.keys() else (pi, pv)\n for pi, pv in parent.items() \n ])\n \n cv = child.copy()\n cv.update(parent)\n parent = cv\n \n return parent\n \n pass\n \n \n def __absolute(self, parent, child):\n \n parent['LISTS']['absolute']['width'] += child['LISTS']['absolute']['width']\n parent['LISTS']['absolute']['height'] += child['LISTS']['absolute']['height']\n parent['LISTS']['absolute']['area'] += child['LISTS']['absolute']['area']\n \n parent['LISTS']['absolute']['font-size'] = self.mergeDicts(\n parent['LISTS']['absolute']['font-size'],\n child['LISTS']['absolute']['font-size']\n )\n \n parent['LISTS']['absolute']['font-family'] = self.mergeDicts(\n parent['LISTS']['absolute']['font-family'],\n child['LISTS']['absolute']['font-family']\n )\n \n parent['LISTS']['absolute']['color'] = self.mergeDicts(\n parent['LISTS']['absolute']['color'],\n child['LISTS']['absolute']['color']\n )\n\n parent['LISTS']['absolute']['background-color'] = self.mergeDicts(\n parent['LISTS']['absolute']['background-color'],\n child['LISTS']['absolute']['background-color']\n )\n \n parent['LISTS']['absolute']['bag-of-classes'] = self.mergeDicts(\n parent['LISTS']['absolute']['bag-of-classes'], \n child['LISTS']['absolute']['bag-of-classes']\n )\n \n parent['LISTS']['absolute']['bag-of-tags'] = self.mergeDicts(\n parent['LISTS']['absolute']['bag-of-tags'], \n child['LISTS']['absolute']['bag-of-tags']\n )\n \n return parent, child\n \n pass\n \n \n def __end_absolute(self, node):\n\n \n return node\n \n pass\n \n \n \n \n def relative(self, node):\n \n self.map(\n self.DOM,\n fun1 = self.__init_relative,\n fun2 = self.__relative\n )\n \n pass\n \n \n def __init_relative(self, node):\n \n \n return node\n pass\n \n \n \n def child_parent_ratio(self, child, parent):\n \n return child / parent if parent != 0 else 0\n \n pass\n \n \n def to_bag_of(self, child, parent):\n \n ratios = [ child[pi]/pv if (pi in child.keys()) == True else 0 for pi,pv in parent.items()]\n \n return ratios\n \n pass\n \n \n \n def __relative(self, parent, child):\n \n child['LISTS']['relative'] = {}\n child['LISTS']['relative']['width'] = self.child_parent_ratio(child['LISTS']['absolute']['width'], parent['LISTS']['absolute']['width'])\n child['LISTS']['relative']['height'] = child['LISTS']['absolute']['height'] / parent['LISTS']['absolute']['height'] if parent['LISTS']['absolute']['height'] != 0 else 0\n child['LISTS']['relative']['area'] = child['LISTS']['absolute']['area'] / parent['LISTS']['absolute']['area'] if parent['LISTS']['absolute']['area'] != 0 else 0\n\n\n child['LISTS']['relative']['tagsCount'] = child['CETD']['tagsCount'] / parent['CETD']['tagsCount'] if parent['CETD']['tagsCount'] != 0 else 0\n\n \n child['LISTS']['relative']['font-size'] = self.to_bag_of(\n child['LISTS']['absolute']['font-size'],\n parent['LISTS']['absolute']['font-size']\n )\n \n child['LISTS']['relative']['font-family'] = self.to_bag_of(\n child['LISTS']['absolute']['font-family'],\n parent['LISTS']['absolute']['font-family']\n )\n \n child['LISTS']['relative']['color'] = self.to_bag_of(\n child['LISTS']['absolute']['color'],\n parent['LISTS']['absolute']['color']\n )\n \n child['LISTS']['relative']['background-color'] = self.to_bag_of(\n child['LISTS']['absolute']['background-color'],\n parent['LISTS']['absolute']['background-color']\n )\n\n child['LISTS']['relative']['bag-of-classes'] = self.to_bag_of(\n child['LISTS']['absolute']['bag-of-classes'],\n parent['LISTS']['absolute']['bag-of-classes']\n )\n \n child['LISTS']['relative']['bag-of-tags'] = self.to_bag_of(\n child['LISTS']['absolute']['bag-of-tags'],\n parent['LISTS']['absolute']['bag-of-tags']\n )\n \n return parent, child\n \n pass\n \n \n \n def adjust(self, node):\n \n self.map(\n node, \n fun1 = self.__init_adjust, \n fun2 = self.__adjust, \n fun4 = self.__end_adjust\n )\n \n pass\n \n def isListTag(self, tagname):\n \n return True if tagname == 'UL' or tagname == 'TR' else False\n \n pass\n \n \n\n def feature_coherence(self, node, absolute_feature, relative_feature):\n \n abs_val = self.get_feature_by_path(node, absolute_feature)\n \n nbr_children = len(node['children'])\n nbr_elements = len(abs_val)\n expected_vect = np.full(nbr_elements, float(1/float(nbr_children)) if nbr_children !=0 else 0) \n \n feature_coherence = pw.vectors_coherence(\n expected_vect,\n [\n self.get_feature_by_path(child, relative_feature) \n for child in node['children']\n ]\n )\n \n \n return feature_coherence\n \n \n pass\n \n \n \n def __init_adjust(self, node):\n \n nbr_children = len(node['children'])\n expected_vect = np.full(nbr_children, float(1/float(nbr_children)) if nbr_children !=0 else 0)\n \n \n node['LISTS']['adjust'] = {}\n node['LISTS']['adjust']['expected_vect'] = list(expected_vect)\n node['LISTS']['adjust']['bag-of-classes-coherence'] = self.feature_coherence(node, 'LISTS.absolute.bag-of-classes', 'LISTS.relative.bag-of-classes')\n node['LISTS']['adjust']['bag-of-tags-coherence'] = self.feature_coherence(node, 'LISTS.absolute.bag-of-tags', 'LISTS.relative.bag-of-tags')\n node['LISTS']['adjust']['width'] = []\n node['LISTS']['adjust']['height'] = []\n node['LISTS']['adjust']['area'] = []\n node['LISTS']['adjust']['background-color'] = self.feature_coherence(node, 'LISTS.absolute.background-color', 'LISTS.relative.background-color')\n node['LISTS']['adjust']['font-size'] = self.feature_coherence(node, 'LISTS.absolute.font-size', 'LISTS.relative.font-size')\n node['LISTS']['adjust']['font-family'] = self.feature_coherence(node, 'LISTS.absolute.font-family', 'LISTS.relative.font-family')\n node['LISTS']['adjust']['color'] = self.feature_coherence(node, 'LISTS.absolute.color', 'LISTS.relative.color')\n\n node['LISTS']['adjust']['tagsCount'] = []\n \n \n node['LISTS']['adjust']['multi-tag-subtree'] = 1 if len(node['children']) >= 2 else 0\n node['LISTS']['adjust']['standard-list-tag'] = 1 if self.isListTag(node['tagName']) else 0\n \n return node\n \n pass\n \n \n def __adjust(self, parent, child):\n \n \n parent['LISTS']['adjust']['width'].append(child['LISTS']['relative']['width'])\n parent['LISTS']['adjust']['height'].append(child['LISTS']['relative']['height'])\n parent['LISTS']['adjust']['area'].append(child['LISTS']['relative']['area'])\n \n parent['LISTS']['adjust']['tagsCount'].append(child['LISTS']['relative']['tagsCount'])\n \n return parent, child\n \n pass\n \n \n def __end_adjust(self, node):\n \n if len(node['LISTS']['adjust']['expected_vect']) != 0:\n node['LISTS']['adjust']['width'] = 1- euclidean_distances([node['LISTS']['adjust']['width']], [node['LISTS']['adjust']['expected_vect']])[0][0]\n node['LISTS']['adjust']['height'] = 1- euclidean_distances([node['LISTS']['adjust']['height']], [node['LISTS']['adjust']['expected_vect']])[0][0]\n node['LISTS']['adjust']['area'] = 1- euclidean_distances([node['LISTS']['adjust']['area']], [node['LISTS']['adjust']['expected_vect']])[0][0]\n node['LISTS']['adjust']['tagsCount'] = 1- euclidean_distances([node['LISTS']['adjust']['tagsCount']], [node['LISTS']['adjust']['expected_vect']])[0][0]\n\n else:\n \n node['LISTS']['adjust']['width'] = 0\n node['LISTS']['adjust']['height'] = 0\n node['LISTS']['adjust']['area'] = 0\n node['LISTS']['adjust']['tagsCount'] = 0\n\n \n pass\n \n# =============================================================================\n# features = [\n# 'xpath','LISTS.adjust.width', 'LISTS.adjust.height', 'LISTS.adjust.area', \n# 'LISTS.adjust.font-size', 'LISTS.adjust.font-family', 'LISTS.adjust.background-color', \n# 'LISTS.adjust.color', 'LISTS.adjust.classes-coherence','LISTS.adjust.tagsCount']\n# \n# final_expected_vect = [1,1,1,1,1,1,1,1,1]\n# \n# self.flatten_single_node(features)\n# =============================================================================\n \n return node\n \n pass\n \n \n def get_final_results(self, xpaths, X):\n \n nbr_nodes = len(xpaths)\n \n for i in range(nbr_nodes):\n node = self.xpath_based_node_search(self.DOM, xpaths[i])\n euclidean_sim = pw.similarity(self.expected_vect, X[i,:], max_val = 0)\n node['LISTS']['coherence'] = str(euclidean_sim)\n \n \n pass\n \n \n \n def mark_results(self, node):\n \n \n self.map(node, fun1 = self.__mark_results)\n \n pass\n \n \n def __mark_results(self,node):\n \n node['LISTS']['mark'] = \"1\" if float(node['LISTS']['coherence']) >= self.coherence_threshold[0] and float(node['LISTS']['coherence']) <= self.coherence_threshold[1] and len(node['children']) > self.sub_tags_threshold else \"0\"\n \n return node\n \n pass\n \n \n \n def markAll(self, xpaths, labels):\n \n for xpath in range(len(xpaths)):\n \n node = self.xpath_based_node_search(self.DOM, xpaths[xpath])\n node['LISTS']['mark'] = str(labels[xpath])\n# node['LISTS'] = {}\n \n pass\n \n \n pass\n \n \n def remove(self, node):\n \n self.map(node, fun1 = self.__remove)\n pass\n \n \n def __remove(self, node):\n \n if len(node['children']) < 4:\n node['LISTS']['mark'] = \"-1\"\n \n return node\n pass\n \n \n pass\n\n\n\n\n\n\nif __name__ == '__main__':\n \n lists = Lists_Detector()\n# cetd = CETD()\n# lists.DOM = DOM\n# lists.meta_data = meta\n# lists.webpage_url= url\n lists.retrieve_DOM_tree(os.path.realpath('../extractor/test.json'))\n lists.apply(lists.DOM, coherence_threshold = (0.80,1), sub_tags_threshold = 1)\n# print(list(lists.DOM['children'][0]['LISTS']['adjust'].values())[1:])\n\n# lists.coherence_threshold =(0.80,1)\n# lists.get_final_results(lists.xpaths, lists.X)\n# lists.mark_results(lists.DOM)\n# lists.DOM_file_path = os.path.realpath('../datasets/extracted_data/0010.json')\n lists.update_DOM_tree()\n# print(lists.DOM['tagsCount'])\n# DOM = lists.DOM\n# meta = lists.meta_data\n# url= lists.webpage_url\n# cetd.count_tags(lists.DOM)\n# cetd.text_density(lists.DOM)\n# cetd.density_sum(lists.DOM)\n# lists.absolute(lists.DOM)\n# lists.relative(lists.DOM)\n# lists.adjust(lists.DOM)\n# print(lists.DOM['children'][0]['children'][0]['children'][0]['LISTS']['adjust']['font-size'])\n# print(len(lists.DOM['children'][0]['children']))\n# features = [\n# 'xpath','LISTS.adjust.width', 'LISTS.adjust.height', 'LISTS.adjust.area', \n# 'LISTS.adjust.font-size', 'LISTS.adjust.font-family', 'LISTS.adjust.background-color', \n# 'LISTS.adjust.color', 'LISTS.adjust.bag-of-classes-coherence','LISTS.adjust.tagsCount']\n# features = ['xpath','LISTS.adjust.bag-of-classes-coherence']\n# \n# arr = lists.flatten(lists.DOM, features = features)\n# xpaths = arr[:,0]\n# X= arr[:,1:]\n# print(X)\n# lists.get_final_results(xpaths, X)\n# lists.mark_results(lists.DOM)\n# print(lists.DOM['children'][0]['children'][4]['LISTS']['adjust']['classes-coherence'])\n# print(lists.DOM['children'][0]['children'][4]['LISTS']['adjust']['bag-of-classes'])\n# print(lists.DOM['children'][0]['textDensity'])\n# print(lists.DOM['children'][0]['textDensity'])\n# print(lists.DOM['children'][1]['textDensity'])\n\n# lists.DOM['LISTS']['relative'] = {}\n# vect = lists.vectorize(node = lists.DOM)\n# print(vect.shape)\n \n# tsne = TSNE(n_components=2).fit_transform(X)\n# km = KMeans(n_clusters = 2)\n# results = km.fit(X)\n \n# fig = plt.figure()\n# ax = fig.add_subplot(111, projection='3d') \n \n# plt.scatter(tsne[:,0], tsne[:,1], c = results.labels_)\n# lists.markAll(xpaths, results.labels_)\n \n # heuristic based method :\n# lists.remove(lists.DOM)\n# lists.update_DOM_tree()\n# df = pd.DataFrame(X)\n# print(df)\n \n pass\n" ]
[ [ "sklearn.metrics.pairwise.euclidean_distances", "pandas.set_option" ] ]
vvekic/serve
[ "f02a56bf1f0de1705fd9f399c1115d36e343c90c" ]
[ "ts/torch_handler/text_classifier.py" ]
[ "# pylint: disable=E1102\n# TODO remove pylint disable comment after https://github.com/pytorch/pytorch/issues/24807 gets merged.\n\"\"\"\nModule for text classification default handler\nDOES NOT SUPPORT BATCH!\n\"\"\"\nimport logging\nimport torch\nimport torch.nn.functional as F\nfrom torchtext.data.utils import ngrams_iterator\nfrom captum.attr import TokenReferenceBase\nfrom .text_handler import TextHandler\nfrom ..utils.util import map_class_to_label\n\nlogger = logging.getLogger(__name__)\n\nclass TextClassifier(TextHandler):\n \"\"\"\n TextClassifier handler class. This handler takes a text (string) and\n as input and returns the classification text based on the model vocabulary.\n \"\"\"\n\n ngrams = 2\n\n def preprocess(self, data):\n \"\"\"Normalizes the input text for PyTorch model using following basic cleanup operations :\n - remove html tags\n - lowercase all text\n - expand contractions [like I'd -> I would, don't -> do not]\n - remove accented characters\n - remove punctuations\n Converts the normalized text to tensor using the source_vocab.\n\n Args:\n data (str): The input data is in the form of a string\n\n Returns:\n (Tensor): Text Tensor is returned after perfoming the pre-processing operations\n (str): The raw input is also returned in this function\n \"\"\"\n\n # Compat layer: normally the envelope should just return the data\n # directly, but older versions of Torchserve didn't have envelope.\n # Processing only the first input, not handling batch inference\n\n line = data[0]\n text = line.get(\"data\") or line.get(\"body\")\n if isinstance(text, (bytes, bytearray)):\n text = text.decode('utf-8')\n\n text = self._remove_html_tags(text)\n text = text.lower()\n text = self._expand_contractions(text)\n text = self._remove_accented_characters(text)\n text = self._remove_punctuation(text)\n text = self._tokenize(text)\n text_tensor = torch.as_tensor(\n [\n self.source_vocab[token]\n for token in ngrams_iterator(text, self.ngrams)\n ],\n device=self.device\n )\n return text_tensor, text\n\n def inference(self, data, *args, **kwargs):\n \"\"\"The Inference Request is made through this function and the user\n needs to override the inference function to customize it.\n\n Args:\n data (torch tensor): The data is in the form of Torch Tensor\n whose shape should match that of the\n Model Input shape.\n\n Returns:\n (Torch Tensor): The predicted response from the model is returned\n in this function.\n \"\"\"\n text_tensor, _ = data\n offsets = torch.as_tensor([0], device=self.device)\n return super().inference(text_tensor, offsets)\n\n def postprocess(self, data):\n \"\"\"\n The post process function converts the prediction response into a\n Torchserve compatible format\n\n Args:\n data (Torch Tensor): The data parameter comes from the prediction output\n output_explain (None): Defaults to None.\n\n Returns:\n (list): Returns the response containing the predictions and explanations\n (if the Endpoint is hit).It takes the form of a list of dictionary.\n \"\"\"\n data = F.softmax(data)\n data = data.tolist()\n return map_class_to_label(data, self.mapping)\n\n def get_insights(self, text_preprocess, _, target=0):\n \"\"\"Calculates the captum insights\n\n Args:\n text_preprocess (tensor): Tensor of the Text Input\n _ (str): The Raw text data specified in the input request\n target (int): Defaults to 0, the user needs to specify the target\n for the captum explanation.\n\n Returns:\n (dict): Returns a dictionary of the word token importances\n \"\"\"\n text_tensor, all_tokens = text_preprocess\n token_reference = TokenReferenceBase()\n logger.info(\"input_text shape %s\", len(text_tensor.shape))\n logger.info(\"get_insights target %s\", target)\n offsets = torch.tensor([0]).to(self.device)\n\n all_tokens = self.get_word_token(all_tokens)\n logger.info(\"text_tensor tokenized shape %s\", text_tensor.shape)\n reference_indices = token_reference.generate_reference(\n text_tensor.shape[0], device=self.device\n ).squeeze(0)\n logger.info(\"reference indices shape %s\", reference_indices.shape)\n\n # all_tokens = self.get_word_token(text)\n attributions = self.lig.attribute(\n text_tensor,\n reference_indices,\n additional_forward_args=(offsets),\n return_convergence_delta=False,\n target=target,\n )\n\n logger.info(\"attributions shape %s\", attributions.shape)\n attributions_sum = self.summarize_attributions(attributions)\n response = {}\n\n response[\"importances\"] = attributions_sum.tolist()\n response[\"words\"] = all_tokens\n return [response]\n" ]
[ [ "torch.as_tensor", "torch.tensor", "torch.nn.functional.softmax" ] ]
PGBI/Surprise
[ "46b9914995e6c8c7d227b46f2eaeef2d4600580f" ]
[ "surprise/model_selection/search.py" ]
[ "from __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\nfrom abc import ABCMeta, abstractmethod\nfrom itertools import product\nimport numpy as np\nfrom joblib import Parallel\nfrom joblib import delayed\nfrom six import moves, string_types, with_metaclass\n\nfrom .split import get_cv\nfrom .validation import fit_and_score\nfrom ..dataset import DatasetUserFolds\nfrom ..utils import get_rng\n\n\nclass BaseSearchCV(with_metaclass(ABCMeta)):\n \"\"\"Base class for hyper parameter search with cross-validation.\"\"\"\n\n @abstractmethod\n def __init__(self, algo_class, measures=['rmse', 'mae'], cv=None,\n refit=False, return_train_measures=False, n_jobs=1,\n pre_dispatch='2*n_jobs', joblib_verbose=0):\n\n self.algo_class = algo_class\n self.measures = [measure.lower() for measure in measures]\n self.cv = cv\n\n if isinstance(refit, string_types):\n if refit.lower() not in self.measures:\n raise ValueError('It looks like the measure you want to use '\n 'with refit ({}) is not in the measures '\n 'parameter')\n\n self.refit = refit.lower()\n\n elif refit is True:\n self.refit = self.measures[0]\n\n else:\n self.refit = False\n\n self.return_train_measures = return_train_measures\n self.n_jobs = n_jobs\n self.pre_dispatch = pre_dispatch\n self.joblib_verbose = joblib_verbose\n\n def _parse_options(self, params):\n # As sim_options and bsl_options are dictionaries, they require a\n # special treatment.\n\n if 'sim_options' in params:\n sim_options = params['sim_options']\n sim_options_list = [dict(zip(sim_options, v)) for v in\n product(*sim_options.values())]\n params['sim_options'] = sim_options_list\n\n if 'bsl_options' in params:\n bsl_options = params['bsl_options']\n bsl_options_list = [dict(zip(bsl_options, v)) for v in\n product(*bsl_options.values())]\n params['bsl_options'] = bsl_options_list\n\n return params\n\n def fit(self, data):\n \"\"\"Runs the ``fit()`` method of the algorithm for all parameter\n combinations, over different splits given by the ``cv`` parameter.\n\n Args:\n data (:obj:`Dataset <surprise.dataset.Dataset>`): The dataset on\n which to evaluate the algorithm, in parallel.\n \"\"\"\n\n if self.refit and isinstance(data, DatasetUserFolds):\n raise ValueError('refit cannot be used when data has been '\n 'loaded with load_from_folds().')\n\n cv = get_cv(self.cv)\n\n delayed_list = (\n delayed(fit_and_score)(self.algo_class(**params), trainset,\n testset, self.measures,\n self.return_train_measures)\n for params, (trainset, testset) in product(self.param_combinations,\n cv.split(data))\n )\n out = Parallel(n_jobs=self.n_jobs,\n pre_dispatch=self.pre_dispatch,\n verbose=self.joblib_verbose)(delayed_list)\n\n (test_measures_dicts,\n train_measures_dicts,\n fit_times,\n test_times) = zip(*out)\n\n # test_measures_dicts is a list of dict like this:\n # [{'mae': 1, 'rmse': 2}, {'mae': 2, 'rmse': 3} ...]\n # E.g. for 5 splits, the first 5 dicts are for the first param\n # combination, the next 5 dicts are for the second param combination,\n # etc...\n # We convert it into a dict of list:\n # {'mae': [1, 2, ...], 'rmse': [2, 3, ...]}\n # Each list is still of size n_parameters_combinations * n_splits.\n # Then, reshape each list to have 2-D arrays of shape\n # (n_parameters_combinations, n_splits). This way we can easily compute\n # the mean and std dev over all splits or over all param comb.\n test_measures = dict()\n train_measures = dict()\n new_shape = (len(self.param_combinations), cv.get_n_folds())\n for m in self.measures:\n test_measures[m] = np.asarray([d[m] for d in test_measures_dicts])\n test_measures[m] = test_measures[m].reshape(new_shape)\n if self.return_train_measures:\n train_measures[m] = np.asarray([d[m] for d in\n train_measures_dicts])\n train_measures[m] = train_measures[m].reshape(new_shape)\n\n cv_results = dict()\n best_index = dict()\n best_params = dict()\n best_score = dict()\n best_estimator = dict()\n for m in self.measures:\n # cv_results: set measures for each split and each param comb\n for split in range(cv.get_n_folds()):\n cv_results['split{0}_test_{1}'.format(split, m)] = \\\n test_measures[m][:, split]\n if self.return_train_measures:\n cv_results['split{0}_train_{1}'.format(split, m)] = \\\n train_measures[m][:, split]\n\n # cv_results: set mean and std over all splits (testset and\n # trainset) for each param comb\n mean_test_measures = test_measures[m].mean(axis=1)\n cv_results['mean_test_{}'.format(m)] = mean_test_measures\n cv_results['std_test_{}'.format(m)] = test_measures[m].std(axis=1)\n if self.return_train_measures:\n mean_train_measures = train_measures[m].mean(axis=1)\n cv_results['mean_train_{}'.format(m)] = mean_train_measures\n cv_results['std_train_{}'.format(m)] = \\\n train_measures[m].std(axis=1)\n\n # cv_results: set rank of each param comb\n indices = cv_results['mean_test_{}'.format(m)].argsort()\n cv_results['rank_test_{}'.format(m)] = np.empty_like(indices)\n cv_results['rank_test_{}'.format(m)][indices] = np.arange(\n len(indices)) + 1 # sklearn starts rankings at 1 as well.\n\n # set best_index, and best_xxxx attributes\n if m in ('mae', 'rmse', 'mse'):\n best_index[m] = mean_test_measures.argmin()\n elif m in ('fcp',):\n best_index[m] = mean_test_measures.argmax()\n best_params[m] = self.param_combinations[best_index[m]]\n best_score[m] = mean_test_measures[best_index[m]]\n best_estimator[m] = self.algo_class(**best_params[m])\n\n # Cv results: set fit and train times (mean, std)\n fit_times = np.array(fit_times).reshape(new_shape)\n test_times = np.array(test_times).reshape(new_shape)\n for s, times in zip(('fit', 'test'), (fit_times, test_times)):\n cv_results['mean_{}_time'.format(s)] = times.mean(axis=1)\n cv_results['std_{}_time'.format(s)] = times.std(axis=1)\n\n # cv_results: set params key and each param_* values\n cv_results['params'] = self.param_combinations\n for param in self.param_combinations[0]:\n cv_results['param_' + param] = [comb[param] for comb in\n self.param_combinations]\n\n if self.refit:\n best_estimator[self.refit].fit(data.build_full_trainset())\n\n self.best_index = best_index\n self.best_params = best_params\n self.best_score = best_score\n self.best_estimator = best_estimator\n self.cv_results = cv_results\n\n def test(self, testset, verbose=False):\n \"\"\"Call ``test()`` on the estimator with the best found parameters\n (according the the ``refit`` parameter). See :meth:`AlgoBase.test()\n <surprise.prediction_algorithms.algo_base.AlgoBase.test>`.\n\n Only available if ``refit`` is not ``False``.\n \"\"\"\n\n if not self.refit:\n raise ValueError('refit is False, cannot use test()')\n\n return self.best_estimator[self.refit].test(testset, verbose)\n\n def predict(self, *args):\n \"\"\"Call ``predict()`` on the estimator with the best found parameters\n (according the the ``refit`` parameter). See :meth:`AlgoBase.predict()\n <surprise.prediction_algorithms.algo_base.AlgoBase.predict>`.\n\n Only available if ``refit`` is not ``False``.\n \"\"\"\n\n if not self.refit:\n raise ValueError('refit is False, cannot use predict()')\n\n return self.best_estimator[self.refit].predict(*args)\n\n\nclass GridSearchCV(BaseSearchCV):\n \"\"\"The :class:`GridSearchCV` class computes accuracy metrics for an\n algorithm on various combinations of parameters, over a cross-validation\n procedure. This is useful for finding the best set of parameters for a\n prediction algorithm. It is analogous to `GridSearchCV\n <http://scikit-learn.org/stable/modules/generated/sklearn.\n model_selection.GridSearchCV.html>`_ from scikit-learn.\n\n See an example in the :ref:`User Guide <tuning_algorithm_parameters>`.\n\n Args:\n algo_class(:obj:`AlgoBase \\\n <surprise.prediction_algorithms.algo_base.AlgoBase>`): The class\n of the algorithm to evaluate.\n param_grid(dict): Dictionary with algorithm parameters as keys and\n list of values as keys. All combinations will be evaluated with\n desired algorithm. Dict parameters such as ``sim_options`` require\n special treatment, see :ref:`this note<grid_search_note>`.\n measures(list of string): The performance measures to compute. Allowed\n names are function names as defined in the :mod:`accuracy\n <surprise.accuracy>` module. Default is ``['rmse', 'mae']``.\n cv(cross-validation iterator, int or ``None``): Determines how the\n ``data`` parameter will be split (i.e. how trainsets and testsets\n will be defined). If an int is passed, :class:`KFold\n <surprise.model_selection.split.KFold>` is used with the\n appropriate ``n_splits`` parameter. If ``None``, :class:`KFold\n <surprise.model_selection.split.KFold>` is used with\n ``n_splits=5``.\n refit(bool or str): If ``True``, refit the algorithm on the whole\n dataset using the set of parameters that gave the best average\n performance for the first measure of ``measures``. Other measures\n can be used by passing a string (corresponding to the measure\n name). Then, you can use the ``test()`` and ``predict()`` methods.\n ``refit`` can only be used if the ``data`` parameter given to\n ``fit()`` hasn't been loaded with :meth:`load_from_folds()\n <surprise.dataset.Dataset.load_from_folds>`. Default is ``False``.\n return_train_measures(bool): Whether to compute performance measures on\n the trainsets. If ``True``, the ``cv_results`` attribute will\n also contain measures for trainsets. Default is ``False``.\n n_jobs(int): The maximum number of parallel training procedures.\n\n - If ``-1``, all CPUs are used.\n - If ``1`` is given, no parallel computing code is used at all,\\\n which is useful for debugging.\n - For ``n_jobs`` below ``-1``, ``(n_cpus + n_jobs + 1)`` are\\\n used. For example, with ``n_jobs = -2`` all CPUs but one are\\\n used.\n\n Default is ``1``.\n pre_dispatch(int or string): Controls the number of jobs that get\n dispatched during parallel execution. Reducing this number can be\n useful to avoid an explosion of memory consumption when more jobs\n get dispatched than CPUs can process. This parameter can be:\n\n - ``None``, in which case all the jobs are immediately created\\\n and spawned. Use this for lightweight and fast-running\\\n jobs, to avoid delays due to on-demand spawning of the\\\n jobs.\n - An int, giving the exact number of total jobs that are\\\n spawned.\n - A string, giving an expression as a function of ``n_jobs``,\\\n as in ``'2*n_jobs'``.\n\n Default is ``'2*n_jobs'``.\n joblib_verbose(int): Controls the verbosity of joblib: the higher, the\n more messages.\n\n Attributes:\n best_estimator (dict of AlgoBase):\n Using an accuracy measure as key, get the algorithm that gave the\n best accuracy results for the chosen measure, averaged over all\n splits.\n best_score (dict of floats):\n Using an accuracy measure as key, get the best average score\n achieved for that measure.\n best_params (dict of dicts):\n Using an accuracy measure as key, get the parameters combination\n that gave the best accuracy results for the chosen measure (on\n average).\n best_index (dict of ints):\n Using an accuracy measure as key, get the index that can be used\n with ``cv_results`` that achieved the highest accuracy for that\n measure (on average).\n cv_results (dict of arrays):\n A dict that contains accuracy measures over all splits, as well as\n train and test time for each parameter combination. Can be imported\n into a pandas `DataFrame` (see :ref:`example\n <cv_results_example>`).\n \"\"\"\n def __init__(self, algo_class, param_grid, measures=['rmse', 'mae'],\n cv=None, refit=False, return_train_measures=False, n_jobs=1,\n pre_dispatch='2*n_jobs', joblib_verbose=0):\n\n super(GridSearchCV, self).__init__(\n algo_class=algo_class, measures=measures, cv=cv, refit=refit,\n return_train_measures=return_train_measures, n_jobs=n_jobs,\n pre_dispatch=pre_dispatch, joblib_verbose=joblib_verbose)\n\n self.param_grid = self._parse_options(param_grid.copy())\n self.param_combinations = [dict(zip(self.param_grid, v)) for v in\n product(*self.param_grid.values())]\n\n\nclass RandomizedSearchCV(BaseSearchCV):\n \"\"\"The :class:`RandomizedSearchCV` class computes accuracy metrics for an\n algorithm on various combinations of parameters, over a cross-validation\n procedure. As opposed to GridSearchCV, which uses an exhaustive\n combinatorial approach, RandomizedSearchCV samples randomly from the\n parameter space. This is useful for finding the best set of parameters\n for a prediction algorithm, especially using a coarse to fine approach.\n It is analogous to `RandomizedSearchCV <http://scikit-learn.org/stable/\n modules/generated/sklearn.model_selection.RandomizedSearchCV.html>`_ from\n scikit-learn.\n\n See an example in the :ref:`User Guide <tuning_algorithm_parameters>`.\n\n Args:\n algo_class(:obj:`AlgoBase \\\n <surprise.prediction_algorithms.algo_base.AlgoBase>`): The class\n of the algorithm to evaluate.\n param_distributions(dict): Dictionary with algorithm parameters as\n keys and distributions or lists of parameters to try. Distributions\n must provide a rvs method for sampling (such as those from\n scipy.stats.distributions). If a list is given, it is sampled\n uniformly. Parameters will be sampled n_iter times.\n n_iter(int): Number of times parameter settings are sampled. Default is\n ``10``.\n measures(list of string): The performance measures to compute. Allowed\n names are function names as defined in the :mod:`accuracy\n <surprise.accuracy>` module. Default is ``['rmse', 'mae']``.\n cv(cross-validation iterator, int or ``None``): Determines how the\n ``data`` parameter will be split (i.e. how trainsets and testsets\n will be defined). If an int is passed, :class:`KFold\n <surprise.model_selection.split.KFold>` is used with the\n appropriate ``n_splits`` parameter. If ``None``, :class:`KFold\n <surprise.model_selection.split.KFold>` is used with\n ``n_splits=5``.\n refit(bool or str): If ``True``, refit the algorithm on the whole\n dataset using the set of parameters that gave the best average\n performance for the first measure of ``measures``. Other measures\n can be used by passing a string (corresponding to the measure\n name). Then, you can use the ``test()`` and ``predict()`` methods.\n ``refit`` can only be used if the ``data`` parameter given to\n ``fit()`` hasn't been loaded with :meth:`load_from_folds()\n <surprise.dataset.Dataset.load_from_folds>`. Default is ``False``.\n return_train_measures(bool): Whether to compute performance measures on\n the trainsets. If ``True``, the ``cv_results`` attribute will\n also contain measures for trainsets. Default is ``False``.\n n_jobs(int): The maximum number of parallel training procedures.\n\n - If ``-1``, all CPUs are used.\n - If ``1`` is given, no parallel computing code is used at all,\\\n which is useful for debugging.\n - For ``n_jobs`` below ``-1``, ``(n_cpus + n_jobs + 1)`` are\\\n used. For example, with ``n_jobs = -2`` all CPUs but one are\\\n used.\n\n Default is ``1``.\n pre_dispatch(int or string): Controls the number of jobs that get\n dispatched during parallel execution. Reducing this number can be\n useful to avoid an explosion of memory consumption when more jobs\n get dispatched than CPUs can process. This parameter can be:\n\n - ``None``, in which case all the jobs are immediately created\\\n and spawned. Use this for lightweight and fast-running\\\n jobs, to avoid delays due to on-demand spawning of the\\\n jobs.\n - An int, giving the exact number of total jobs that are\\\n spawned.\n - A string, giving an expression as a function of ``n_jobs``,\\\n as in ``'2*n_jobs'``.\n\n Default is ``'2*n_jobs'``.\n random_state(int, RandomState or None): Pseudo random number\n generator seed used for random uniform sampling from lists of\n possible values instead of scipy.stats distributions. If int,\n ``random_state`` is the seed used by the random number generator.\n If ``RandomState`` instance, ``random_state`` is the random number\n generator. If ``None``, the random number generator is the\n RandomState instance used by ``np.random``. Default is ``None``.\n joblib_verbose(int): Controls the verbosity of joblib: the higher, the\n more messages.\n\n Attributes:\n best_estimator (dict of AlgoBase):\n Using an accuracy measure as key, get the algorithm that gave the\n best accuracy results for the chosen measure, averaged over all\n splits.\n best_score (dict of floats):\n Using an accuracy measure as key, get the best average score\n achieved for that measure.\n best_params (dict of dicts):\n Using an accuracy measure as key, get the parameters combination\n that gave the best accuracy results for the chosen measure (on\n average).\n best_index (dict of ints):\n Using an accuracy measure as key, get the index that can be used\n with ``cv_results`` that achieved the highest accuracy for that\n measure (on average).\n cv_results (dict of arrays):\n A dict that contains accuracy measures over all splits, as well as\n train and test time for each parameter combination. Can be imported\n into a pandas `DataFrame` (see :ref:`example\n <cv_results_example>`).\n \"\"\"\n def __init__(self, algo_class, param_distributions, n_iter=10,\n measures=['rmse', 'mae'], cv=None, refit=False,\n return_train_measures=False, n_jobs=1,\n pre_dispatch='2*n_jobs', random_state=None, joblib_verbose=0):\n\n super(RandomizedSearchCV, self).__init__(\n algo_class=algo_class, measures=measures, cv=cv, refit=refit,\n return_train_measures=return_train_measures, n_jobs=n_jobs,\n pre_dispatch=pre_dispatch, joblib_verbose=joblib_verbose)\n\n self.n_iter = n_iter\n self.random_state = random_state\n self.param_distributions = self._parse_options(\n param_distributions.copy())\n self.param_combinations = self._sample_parameters(\n self.param_distributions, self.n_iter, self.random_state)\n\n @staticmethod\n def _sample_parameters(param_distributions, n_iter, random_state=None):\n \"\"\"Samples ``n_iter`` parameter combinations from\n ``param_distributions`` using ``random_state`` as a seed.\n\n Non-deterministic iterable over random candidate combinations for\n hyper-parameter search. If all parameters are presented as a list,\n sampling without replacement is performed. If at least one parameter\n is given as a distribution, sampling with replacement is used.\n It is highly recommended to use continuous distributions for continuous\n parameters.\n\n Note that before SciPy 0.16, the ``scipy.stats.distributions`` do not\n accept a custom RNG instance and always use the singleton RNG from\n ``numpy.random``. Hence setting ``random_state`` will not guarantee a\n deterministic iteration whenever ``scipy.stats`` distributions are used\n to define the parameter search space. Deterministic behavior is however\n guaranteed from SciPy 0.16 onwards.\n\n Args:\n param_distributions(dict): Dictionary where the keys are\n parameters and values are distributions from which a parameter\n is to be sampled. Distributions either have to provide a\n ``rvs`` function to sample from them, or can be given as a list\n of values, where a uniform distribution is assumed.\n n_iter(int): Number of parameter settings produced.\n Default is ``10``.\n random_state(int, RandomState instance or None):\n Pseudo random number generator seed used for random uniform\n sampling from lists of possible values instead of scipy.stats\n distributions. If ``None``, the random number generator is the\n random state instance used by np.random. Default is ``None``.\n\n Returns:\n combos(list): List of parameter dictionaries with sampled values.\n \"\"\"\n\n # check if all distributions are given as lists\n # if so, sample without replacement\n all_lists = np.all([not hasattr(v, 'rvs')\n for v in param_distributions.values()])\n rnd = get_rng(random_state)\n\n # sort for reproducibility\n items = sorted(param_distributions.items())\n\n if all_lists:\n # create exhaustive combinations\n param_grid = [dict(zip(param_distributions, v)) for v in\n product(*param_distributions.values())]\n combos = np.random.choice(param_grid, n_iter, replace=False)\n\n else:\n combos = []\n for _ in moves.range(n_iter):\n params = dict()\n for k, v in items:\n if hasattr(v, 'rvs'):\n params[k] = v.rvs(random_state=rnd)\n else:\n params[k] = v[rnd.randint(len(v))]\n combos.append(params)\n\n return combos\n" ]
[ [ "numpy.array", "numpy.random.choice", "numpy.asarray", "numpy.empty_like" ] ]
tanyanair/segmentation_uncertainty
[ "197064039a33effe7405d26f048c3daf352413f1" ]
[ "bunet/utils/tf_metrics.py" ]
[ "\"\"\"\nTensorflow implementation of metrics and utils\n\"\"\"\nimport tensorflow as tf\n\nEPSILON = 1e-5\n_smooth = 1\n\n\ndef dice_coef(y_tru, y_prd):\n y_tru = tf.reshape(y_tru, [2, -1])\n y_prd = tf.reshape(y_prd, [2, -1])\n y_prd_pr = tf.sigmoid(y_prd)\n intersection = tf.reduce_sum(y_prd_pr * y_tru, 0)\n union = tf.reduce_sum(y_prd_pr, 0) + tf.reduce_sum(y_tru, 0)\n dice = (2. * intersection + _smooth) / (union + _smooth)\n return tf.reduce_mean(dice)\n\ndef dice_coef_loss(y_tru, y_prd):\n return -dice_coef(y_tru, y_prd)\n\ndef weighted_mc_xentropy(y_tru, mu, log_var, nb_mc, weight, batch_size):\n mu_mc = tf.tile(mu, [1, 1, 1, 1, nb_mc])\n std = tf.exp(log_var)\n # hard coded the known shape of the data\n noise = tf.random_normal((batch_size, 192, 192, 64, nb_mc)) * std\n prd = mu_mc + noise\n\n y_tru = tf.tile(y_tru, [1, 1, 1, 1, nb_mc])\n mc_x = tf.nn.weighted_cross_entropy_with_logits(targets=y_tru, logits=prd, pos_weight=weight)\n # mean across mc samples\n mc_x = tf.reduce_mean(mc_x, -1)\n # mean across every thing else\n return tf.reduce_mean(mc_x)\n\n" ]
[ [ "tensorflow.exp", "tensorflow.nn.weighted_cross_entropy_with_logits", "tensorflow.sigmoid", "tensorflow.reshape", "tensorflow.reduce_sum", "tensorflow.tile", "tensorflow.reduce_mean", "tensorflow.random_normal" ] ]
GregorySchwing/alchemlyb
[ "6eb1f537e1dbc81cf65c4f53267acc75812459b2" ]
[ "src/alchemlyb/parsing/gomc.py" ]
[ "\"\"\"Parsers for extracting alchemical data from `GOMC <http://gomc.eng.wayne.edu/>`_ output files.\n\n\"\"\"\nimport pandas as pd\nimport numpy as np\nfrom .util import anyopen\n\n\n# TODO: perhaps move constants elsewhere?\n# these are the units we need for dealing with GOMC, so not\n# a bad place for it, honestly\n# (kB in kJ/molK)\nk_b = 8.3144621E-3\n\n\ndef extract_u_nk(filename, T):\n \"\"\"Return reduced potentials `u_nk` from a Hamiltonian differences dat file.\n\n Parameters\n ----------\n filename : str\n Path to free energy file to extract data from.\n T : float\n Temperature in Kelvin at which the simulation was sampled.\n\n Returns\n -------\n u_nk : DataFrame\n Potential energy for each alchemical state (k) for each frame (n).\n\n \"\"\"\n\n dh_col_match = \"dU/dL\"\n h_col_match = \"DelE\"\n pv_col_match = 'PV'\n u_col_match = ['Total_En']\n beta = 1/(k_b * T)\n\n state, lambdas, statevec = _extract_state(filename)\n\n # extract a DataFrame from free energy file data\n df = _extract_dataframe(filename)\n\n times = df[df.columns[0]]\n\n # want to grab only dH columns\n DHcols = [col for col in df.columns if (h_col_match in col)]\n dH = df[DHcols]\n\n # GOMC also gives us pV directly; need this for reduced potential\n pv_cols = [col for col in df.columns if (pv_col_match in col)]\n pv = None\n if pv_cols:\n pv = df[pv_cols[0]]\n\n # GOMC also gives us total energy U directly; need this for reduced potential\n u_cols = [col for col in df.columns if any(single_u_col_match in col for single_u_col_match in u_col_match)]\n u = None\n if u_cols:\n u = df[u_cols[0]]\n\n u_k = dict()\n cols = list()\n for col in dH:\n u_col = eval(col.split('->')[1][:-1])\n # calculate reduced potential u_k = dH + pV + U\n u_k[u_col] = beta * dH[col].values\n if pv_cols:\n u_k[u_col] += beta * pv.values\n if u_cols:\n u_k[u_col] += beta * u.values\n cols.append(u_col)\n\n u_k = pd.DataFrame(u_k, columns=cols,\n index=pd.Index(times.values, name='time',dtype=np.float64))\n\n # Need to modify the lambda name\n cols = [l + \"-lambda\" for l in lambdas]\n # create columns for each lambda, indicating state each row sampled from\n for i, l in enumerate(cols):\n u_k[l] = statevec[i]\n\n # set up new multi-index\n newind = ['time'] + cols\n u_k = u_k.reset_index().set_index(newind)\n\n u_k.name = 'u_nk'\n\n return u_k\n\n\ndef extract_dHdl(filename, T):\n \"\"\"Return gradients `dH/dl` from a Hamiltonian differences free energy file.\n\n Parameters\n ----------\n filename : str\n Path to free energy file to extract data from.\n T : float\n Temperature in Kelvin at which the simulation was sampled.\n\n Returns\n -------\n dH/dl : Series\n dH/dl as a function of step for this lambda window.\n\n \"\"\"\n beta = 1/(k_b * T)\n\n state, lambdas, statevec = _extract_state(filename)\n\n # extract a DataFrame from free energy data\n df = _extract_dataframe(filename)\n\n times = df[df.columns[0]]\n\n # want to grab only dH/dl columns\n dHcols = []\n for l in lambdas:\n dHcols.extend([col for col in df.columns if (l in col)])\n\n dHdl = df[dHcols]\n\n # make dimensionless\n dHdl *= beta\n\n dHdl = pd.DataFrame(dHdl.values, columns=lambdas,\n index=pd.Index(times.values, name='time',dtype=np.float64))\n\n # Need to modify the lambda name\n cols = [l + \"-lambda\" for l in lambdas]\n # create columns for each lambda, indicating state each row sampled from\n for i, l in enumerate(cols):\n dHdl[l] = statevec[i]\n\n # set up new multi-index\n newind = ['time'] + cols\n dHdl= dHdl.reset_index().set_index(newind)\n\n dHdl.name='dH/dl'\n\n return dHdl\n\n\ndef _extract_state(filename):\n \"\"\"Extract information on state sampled, names of lambdas.\n\n \"\"\"\n state = None\n with anyopen(filename, 'r') as f:\n for line in f:\n if ('#' in line) and ('State' in line):\n state = int(line.split('State')[1].split(':')[0])\n # GOMC always print these two fields\n lambdas = ['Coulomb', 'VDW']\n statevec = eval(line.strip().split(' = ')[-1])\n break\n\n return state, lambdas, statevec\n\n\ndef _extract_dataframe(filename):\n \"\"\"Extract a DataFrame from free energy data.\n\n \"\"\"\n dh_col_match = \"dU/dL\"\n h_col_match = \"DelE\"\n pv_col_match = 'PV'\n u_col_match = 'Total_En'\n\n xaxis = \"time\"\n with anyopen(filename, 'r') as f:\n names = []\n rows = []\n for line in f:\n line = line.strip()\n if len(line) == 0:\n # avoid parsing empty line\n continue\n elif line.startswith('#T'):\n # this line has state information. No need to be parsed\n continue\n elif line.startswith(\"#Steps\"):\n # read the headers\n elements = line.split()\n for i, element in enumerate(elements):\n if element.startswith(u_col_match):\n names.append(element)\n elif element.startswith(dh_col_match):\n names.append(element)\n elif element.startswith(h_col_match):\n names.append(element)\n elif element.startswith(pv_col_match):\n names.append(element)\n else:\n # parse line as floats\n row = map(float, line.split())\n rows.append(row)\n\n cols = [xaxis]\n cols.extend(names)\n\n return pd.DataFrame(rows, columns=cols)\n" ]
[ [ "pandas.DataFrame", "pandas.Index" ] ]
elvinmirzazadeh/Machine_Learning_A_Z
[ "179b881e343958bac41a717a17b9c4ec55e8d060" ]
[ "Part 3 - Classification/Section 17 - Kernel SVM/kernel_svm.py" ]
[ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndataset = pd.read_csv('data/Social_Network_Ads.csv')\nX = dataset.iloc[:, 2:-1].values\ny = dataset.iloc[:, -1].values\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, \n random_state = 0, shuffle = True)\n\n\n#Feature scaling\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)\n\n#-------------------Fitting SVM on traindata\nfrom sklearn.svm import SVC \nsvc = SVC(kernel='rbf', random_state=0)\nsvc.fit(X_train, y_train)\nacc = svc.score(X_train, y_train)\ny_pred = svc.predict(X_test)\n\n#-------------------Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_test, y_pred)\n\n\nplt.plot(y_test)\nplt.plot(y_pred, color='red')\nplt.show()\n\n\n\n#-------------------Visualising Trainig results\nfrom matplotlib.colors import ListedColormap\nX_set, y_set = X_train, y_train\n\nX1, X2 = np.meshgrid(np.arange(start=X_set[:, 0].min() - 1, stop = X_set[:,0].max() + 1, step=0.01),\n np.arange(start=X_set[:, 1].min() - 1, stop = X_set[:,1].max() + 1, step=0.01))\n\nplt.contourf(X1, X2, svc.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),\n alpha=0.15, cmap=ListedColormap(('red', 'green')))\n\nplt.xlim(X1.min(), X1.max())\nplt.ylim(X2.min(), X2.max())\n\nfor i, j in enumerate(np.unique(y_set)):\n plt.scatter(X_set[y_set==j, 0], X_set[y_set==j, 1],\n c = ListedColormap(('red', 'green'))(i), label=j)\nplt.title = 'Training Set'\nplt.show()\n\n\n#-------------------Visualising Test4 results\nfrom matplotlib.colors import ListedColormap\nX_set, y_set = X_test, y_test\n\nX1, X2 = np.meshgrid(np.arange(start=X_set[:, 0].min() - 1, stop = X_set[:,0].max() + 1, step=0.01),\n np.arange(start=X_set[:, 1].min() - 1, stop = X_set[:,1].max() + 1, step=0.01))\n\nplt.contourf(X1, X2, svc.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),\n alpha=0.15, cmap=ListedColormap(('red', 'green')))\n\nplt.xlim(X1.min(), X1.max())\nplt.ylim(X2.min(), X2.max())\n\nfor i, j in enumerate(np.unique(y_set)):\n plt.scatter(X_set[y_set==j, 0], X_set[y_set==j, 1],\n c = ListedColormap(('red', 'green'))(i), label=j)\nplt.title = 'Test Set'\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\n\n\n\n" ]
[ [ "sklearn.metrics.confusion_matrix", "sklearn.preprocessing.StandardScaler", "matplotlib.pyplot.plot", "matplotlib.colors.ListedColormap", "sklearn.svm.SVC", "sklearn.model_selection.train_test_split", "matplotlib.pyplot.show", "pandas.read_csv", "numpy.unique" ] ]
testouya/mlu-ops
[ "68b0d568868bb7b5057ef67bff315a0db49cd690" ]
[ "bangpy-ops/ops/pairwise_distance/test_pairwise_distance.py" ]
[ "# Copyright (C) [2021] by Cambricon, Inc.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n# pylint: disable=missing-docstring, invalid-name, too-many-locals\n\"\"\"A multi-platform code link example test for BANGPy TCP.\"\"\"\nimport math\nimport numpy as np\nimport torch\nimport pytest\nimport bangpy as bp\nfrom bangpy.common import load_op_by_type\nfrom pairwise_distance import KERNEL_NAME, TARGET_LIST\nfrom pairwise_distance import DTYPES\n\n\ndef create_random_shape(length, size):\n return np.random.randint(low=1, high=size, size=length)\n\n\n\nranshp = create_random_shape(2, 512)\nranshp1 = create_random_shape(5, 3)\nranshp2 = create_random_shape(10, 2)\n\[email protected](\n \"shape\",\n [\n [(1, 2, 10241 * 100 ), (1, 2, 10241 * 100)],\n [(2, 1, 1, 1, 3, 2, 2, 3, 1, 2, 5, 4 ), (5, 4,)],\n [(30000, 1), (30000, 1)],\n [(1, 3), (1, 3)],\n [(4,5,2), (234)],\n [(1, 482 * 1024), (1, 482 * 1024)],\n [(32, 482 * 1024), (32, 482 * 1024)],\n [ranshp, ranshp],\n [ranshp1, ranshp1],\n [ranshp2, ranshp2],\n [[112, 2], [2]],\n [[112, 12], [1]]\n ],\n)\n\n\[email protected](\n \"dtype\", DTYPES,\n)\n\[email protected](\n \"p\", [1, 2.2, 3.5, -1.2],\n)\n\[email protected](\n \"eps\", [0.000001, 0.0001],\n)\n\[email protected](\n \"keepdim\", [False, True],\n)\n\n\n\ndef test_pairwise_distance(target, shape, p, eps, keepdim, dtype):\n if target not in TARGET_LIST:\n return\n\n def mlu_pairwise_distance(p, eps, keepdim):\n def get_total_size(shp):\n size = 1\n for s in shp:\n size *= s\n return size\n\n def check_shape(s1, s2):\n if len(s2) == 1:\n if s2[0] == 1:\n return True\n\n offset = len(s1) - len(s2)\n i = 0\n for _ in s2:\n if s1[offset + i] != s2[i]:\n return False\n i += 1\n return True\n\n def f(a, b):\n if len(a) == 0 or len(b) == 0:\n raise Exception(\"shape err\")\n\n if len(a.shape) == 1 and len(b.shape) == 1:\n raise Exception(\"shape err\")\n\n #拿到shape\n if len(a.shape) > len(b.shape):\n _shape1 = a.shape\n _shape2 = b.shape\n else:\n _shape1 = b.shape\n _shape2 = a.shape\n\n if not check_shape(_shape1, _shape2):\n raise Exception(\"shape err\")\n\n\n _dev = bp.device(0)\n\n dim_index = len(_shape1) - 1\n\n # mlu 输入参数\n _pd_len = _shape1[len(_shape1) - 1]\n _pd_height = 1\n _pd_width = 1\n\n for i in range(0, dim_index + 1):\n _pd_height *= _shape1[i]\n\n if dim_index == len(_shape1) - 1:\n pass\n else:\n for i in range(dim_index + 1, len(_shape1)):\n _pd_width *= _shape1[i]\n\n # mlu 输入\n _mlu_input1 = bp.Array(a.flatten(), _dev)\n _mlu_input2 = bp.Array(b.flatten(), _dev)\n paras = np.array([p, eps]).astype(dtype.as_numpy_dtype) # 这里需要考虑\n _mlu_paras = bp.Array(paras, _dev)\n\n # mlu 输出\n _output_len = get_total_size(_shape1) // _shape1[dim_index]\n output_buffer = np.zeros(_output_len, dtype=dtype.as_numpy_dtype)\n _mlu_output = bp.Array(output_buffer, _dev)\n\n output_count = 256\n output_buffer2 = np.zeros(output_count, dtype=dtype.as_numpy_dtype)\n _mlu_border_output = bp.Array(output_buffer2, _dev)\n\n output_buffer3 = -np.ones(output_count, dtype=np.int32)\n _mlu_border_idx_output = bp.Array(output_buffer3, _dev)\n\n # 调用mlu\n func = load_op_by_type(KERNEL_NAME, dtype.name)\n func(_mlu_input1, _mlu_input2,\n _mlu_paras,\n get_total_size(_shape1), get_total_size(_shape2),\n _pd_len, _pd_height, _pd_width, _output_len\n , _mlu_border_output, _mlu_border_idx_output, _mlu_output)\n\n result = _mlu_output.numpy()\n result_border_idx = _mlu_border_idx_output.numpy()\n\n #收尾\n s = set()\n for i in result_border_idx:\n s.add(i)\n\n for item in s:\n if item >= 0:\n result[item] = math.pow(result[item], 1 / p)\n\n\n def create_output_shape(shp, dim_idx):\n outputshape = []\n if keepdim:\n for item in shp:\n outputshape.append(item)\n outputshape[dim_idx] = 1\n else:\n for i in range(0, len(shp) - 1):\n outputshape.append(shp[i])\n return outputshape\n\n return result.reshape(create_output_shape(_shape1, dim_index))\n\n return f\n\n\n m_ori_input1 = np.random.uniform(low=-5, high=5, size=shape[0])\n m_ori_input2 = np.random.uniform(low=-5, high=5, size=shape[1])\n\n try:\n mlu_ret = mlu_pairwise_distance(p=p, eps=eps, keepdim=keepdim)\\\n (m_ori_input1.astype(dtype.as_numpy_dtype), \\\n m_ori_input2.astype(dtype.as_numpy_dtype))\n except Exception as err:\n print(str(err))\n if str(err) == \"shape err\":\n return\n\n raise Exception(str(err)) from err\n\n\n cpu_ret = torch.nn.PairwiseDistance(p=p, eps=eps, keepdim=keepdim)\\\n (torch.Tensor(m_ori_input1), torch.Tensor(m_ori_input2)).numpy()\n\n bp.assert_allclose(cpu_ret, mlu_ret, rtol = 0.01, atol = 0.01)\n" ]
[ [ "numpy.array", "numpy.zeros", "numpy.ones", "numpy.random.uniform", "numpy.random.randint", "torch.nn.PairwiseDistance", "torch.Tensor" ] ]
TanZheling/mmclassification
[ "1c3ff80f4f8a0b57a57eb08f2325a0c4befb7201" ]
[ "mmcls/models/utils/attention.py" ]
[ "# Copyright (c) OpenMMLab. All rights reserved.\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom mmcv.cnn.bricks.registry import DROPOUT_LAYERS\nfrom mmcv.cnn.bricks.transformer import build_dropout\nfrom mmcv.cnn.utils.weight_init import trunc_normal_\nfrom mmcv.runner.base_module import BaseModule\n\nfrom ..builder import ATTENTION\nfrom .helpers import to_2tuple\n\n\nclass WindowMSA(BaseModule):\n \"\"\"Window based multi-head self-attention (W-MSA) module with relative\n position bias.\n\n Args:\n embed_dims (int): Number of input channels.\n window_size (tuple[int]): The height and width of the window.\n num_heads (int): Number of attention heads.\n qkv_bias (bool, optional): If True, add a learnable bias to q, k, v.\n Defaults to True.\n qk_scale (float, optional): Override default qk scale of\n ``head_dim ** -0.5`` if set. Defaults to None.\n attn_drop (float, optional): Dropout ratio of attention weight.\n Defaults to 0.\n proj_drop (float, optional): Dropout ratio of output. Defaults to 0.\n init_cfg (dict, optional): The extra config for initialization.\n Defaults to None.\n \"\"\"\n\n def __init__(self,\n embed_dims,\n window_size,\n num_heads,\n qkv_bias=True,\n qk_scale=None,\n attn_drop=0.,\n proj_drop=0.,\n init_cfg=None):\n\n super().__init__(init_cfg)\n self.embed_dims = embed_dims\n self.window_size = window_size # Wh, Ww\n self.num_heads = num_heads\n head_embed_dims = embed_dims // num_heads\n self.scale = qk_scale or head_embed_dims**-0.5\n\n # define a parameter table of relative position bias\n self.relative_position_bias_table = nn.Parameter(\n torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1),\n num_heads)) # 2*Wh-1 * 2*Ww-1, nH\n\n # About 2x faster than original impl\n Wh, Ww = self.window_size\n rel_index_coords = self.double_step_seq(2 * Ww - 1, Wh, 1, Ww)\n rel_position_index = rel_index_coords + rel_index_coords.T\n rel_position_index = rel_position_index.flip(1).contiguous()\n self.register_buffer('relative_position_index', rel_position_index)\n\n self.qkv = nn.Linear(embed_dims, embed_dims * 3, bias=qkv_bias)\n self.attn_drop = nn.Dropout(attn_drop)\n self.proj = nn.Linear(embed_dims, embed_dims)\n self.proj_drop = nn.Dropout(proj_drop)\n\n self.softmax = nn.Softmax(dim=-1)\n\n def init_weights(self):\n super(WindowMSA, self).init_weights()\n\n trunc_normal_(self.relative_position_bias_table, std=0.02)\n\n def forward(self, x, mask=None):\n \"\"\"\n Args:\n\n x (tensor): input features with shape of (num_windows*B, N, C)\n mask (tensor, Optional): mask with shape of (num_windows, Wh*Ww,\n Wh*Ww), value should be between (-inf, 0].\n \"\"\"\n B_, N, C = x.shape\n qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads,\n C // self.num_heads).permute(2, 0, 3, 1, 4)\n q, k, v = qkv[0], qkv[1], qkv[\n 2] # make torchscript happy (cannot use tensor as tuple)\n\n q = q * self.scale\n attn = (q @ k.transpose(-2, -1))\n\n relative_position_bias = self.relative_position_bias_table[\n self.relative_position_index.view(-1)].view(\n self.window_size[0] * self.window_size[1],\n self.window_size[0] * self.window_size[1],\n -1) # Wh*Ww,Wh*Ww,nH\n relative_position_bias = relative_position_bias.permute(\n 2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww\n attn = attn + relative_position_bias.unsqueeze(0)\n\n if mask is not None:\n nW = mask.shape[0]\n attn = attn.view(B_ // nW, nW, self.num_heads, N,\n N) + mask.unsqueeze(1).unsqueeze(0)\n attn = attn.view(-1, self.num_heads, N, N)\n attn = self.softmax(attn)\n else:\n attn = self.softmax(attn)\n\n attn = self.attn_drop(attn)\n\n x = (attn @ v).transpose(1, 2).reshape(B_, N, C)\n x = self.proj(x)\n x = self.proj_drop(x)\n return x\n\n @staticmethod\n def double_step_seq(step1, len1, step2, len2):\n seq1 = torch.arange(0, step1 * len1, step1)\n seq2 = torch.arange(0, step2 * len2, step2)\n return (seq1[:, None] + seq2[None, :]).reshape(1, -1)\n\n\[email protected]_module()\nclass ShiftWindowMSA(BaseModule):\n \"\"\"Shift Window Multihead Self-Attention Module.\n\n Args:\n embed_dims (int): Number of input channels.\n input_resolution (Tuple[int, int]): The resolution of the input feature\n map.\n num_heads (int): Number of attention heads.\n window_size (int): The height and width of the window.\n shift_size (int, optional): The shift step of each window towards\n right-bottom. If zero, act as regular window-msa. Defaults to 0.\n qkv_bias (bool, optional): If True, add a learnable bias to q, k, v.\n Default: True\n qk_scale (float | None, optional): Override default qk scale of\n head_dim ** -0.5 if set. Defaults to None.\n attn_drop (float, optional): Dropout ratio of attention weight.\n Defaults to 0.0.\n proj_drop (float, optional): Dropout ratio of output. Defaults to 0.\n dropout_layer (dict, optional): The dropout_layer used before output.\n Defaults to dict(type='DropPath', drop_prob=0.).\n auto_pad (bool, optional): Auto pad the feature map to be divisible by\n window_size, Defaults to False.\n init_cfg (dict, optional): The extra config for initialization.\n Default: None.\n \"\"\"\n\n def __init__(self,\n embed_dims,\n input_resolution,\n num_heads,\n window_size,\n shift_size=0,\n qkv_bias=True,\n qk_scale=None,\n attn_drop=0,\n proj_drop=0,\n dropout_layer=dict(type='DropPath', drop_prob=0.),\n auto_pad=False,\n init_cfg=None):\n super().__init__(init_cfg)\n\n self.embed_dims = embed_dims\n self.input_resolution = input_resolution\n self.shift_size = shift_size\n self.window_size = window_size\n if min(self.input_resolution) <= self.window_size:\n # if window size is larger than input resolution, don't partition\n self.shift_size = 0\n self.window_size = min(self.input_resolution)\n\n self.w_msa = WindowMSA(embed_dims, to_2tuple(self.window_size),\n num_heads, qkv_bias, qk_scale, attn_drop,\n proj_drop)\n\n self.drop = build_dropout(dropout_layer)\n\n H, W = self.input_resolution\n # Handle auto padding\n self.auto_pad = auto_pad\n if self.auto_pad:\n self.pad_r = (self.window_size -\n W % self.window_size) % self.window_size\n self.pad_b = (self.window_size -\n H % self.window_size) % self.window_size\n self.H_pad = H + self.pad_b\n self.W_pad = W + self.pad_r\n else:\n H_pad, W_pad = self.input_resolution\n assert H_pad % self.window_size + W_pad % self.window_size == 0,\\\n f'input_resolution({self.input_resolution}) is not divisible '\\\n f'by window_size({self.window_size}). Please check feature '\\\n f'map shape or set `auto_pad=True`.'\n self.H_pad, self.W_pad = H_pad, W_pad\n self.pad_r, self.pad_b = 0, 0\n\n if self.shift_size > 0:\n # calculate attention mask for SW-MSA\n img_mask = torch.zeros((1, self.H_pad, self.W_pad, 1)) # 1 H W 1\n h_slices = (slice(0, -self.window_size),\n slice(-self.window_size,\n -self.shift_size), slice(-self.shift_size, None))\n w_slices = (slice(0, -self.window_size),\n slice(-self.window_size,\n -self.shift_size), slice(-self.shift_size, None))\n cnt = 0\n for h in h_slices:\n for w in w_slices:\n img_mask[:, h, w, :] = cnt\n cnt += 1\n\n # nW, window_size, window_size, 1\n mask_windows = self.window_partition(img_mask)\n mask_windows = mask_windows.view(\n -1, self.window_size * self.window_size)\n attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)\n attn_mask = attn_mask.masked_fill(attn_mask != 0,\n float(-100.0)).masked_fill(\n attn_mask == 0, float(0.0))\n else:\n attn_mask = None\n\n self.register_buffer('attn_mask', attn_mask)\n\n def forward(self, query):\n H, W = self.input_resolution\n B, L, C = query.shape\n assert L == H * W, 'input feature has wrong size'\n query = query.view(B, H, W, C)\n\n if self.pad_r or self.pad_b:\n query = F.pad(query, (0, 0, 0, self.pad_r, 0, self.pad_b))\n\n # cyclic shift\n if self.shift_size > 0:\n shifted_query = torch.roll(\n query,\n shifts=(-self.shift_size, -self.shift_size),\n dims=(1, 2))\n else:\n shifted_query = query\n\n # nW*B, window_size, window_size, C\n query_windows = self.window_partition(shifted_query)\n # nW*B, window_size*window_size, C\n query_windows = query_windows.view(-1, self.window_size**2, C)\n\n # W-MSA/SW-MSA (nW*B, window_size*window_size, C)\n attn_windows = self.w_msa(query_windows, mask=self.attn_mask)\n\n # merge windows\n attn_windows = attn_windows.view(-1, self.window_size,\n self.window_size, C)\n\n # B H' W' C\n shifted_x = self.window_reverse(attn_windows, self.H_pad, self.W_pad)\n # reverse cyclic shift\n if self.shift_size > 0:\n x = torch.roll(\n shifted_x,\n shifts=(self.shift_size, self.shift_size),\n dims=(1, 2))\n else:\n x = shifted_x\n\n if self.pad_r or self.pad_b:\n x = x[:, :H, :W, :].contiguous()\n\n x = x.view(B, H * W, C)\n\n x = self.drop(x)\n return x\n\n def window_reverse(self, windows, H, W):\n window_size = self.window_size\n B = int(windows.shape[0] / (H * W / window_size / window_size))\n x = windows.view(B, H // window_size, W // window_size, window_size,\n window_size, -1)\n x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)\n return x\n\n def window_partition(self, x):\n B, H, W, C = x.shape\n window_size = self.window_size\n x = x.view(B, H // window_size, window_size, W // window_size,\n window_size, C)\n windows = x.permute(0, 1, 3, 2, 4, 5).contiguous()\n windows = windows.view(-1, window_size, window_size, C)\n return windows\n\n\nclass MultiheadAttention(BaseModule):\n \"\"\"Multi-head Attention Module.\n\n This module implements multi-head attention that supports different input\n dims and embed dims. And it also supports a shortcut from ``value``, which\n is useful if input dims is not the same with embed dims.\n\n Args:\n embed_dims (int): The embedding dimension.\n num_heads (int): Parallel attention heads.\n input_dims (int, optional): The input dimension, and if None,\n use ``embed_dims``. Defaults to None.\n attn_drop (float): Dropout rate of the dropout layer after the\n attention calculation of query and key. Defaults to 0.\n proj_drop (float): Dropout rate of the dropout layer after the\n output projection. Defaults to 0.\n dropout_layer (dict): The dropout config before adding the shortcut.\n Defaults to ``dict(type='Dropout', drop_prob=0.)``.\n qkv_bias (bool): If True, add a learnable bias to q, k, v.\n Defaults to True.\n qk_scale (float, optional): Override default qk scale of\n ``head_dim ** -0.5`` if set. Defaults to None.\n proj_bias (bool) If True, add a learnable bias to output projection.\n Defaults to True.\n v_shortcut (bool): Add a shortcut from value to output. It's usually\n used if ``input_dims`` is different from ``embed_dims``.\n Defaults to False.\n init_cfg (dict, optional): The Config for initialization.\n Defaults to None.\n \"\"\"\n\n def __init__(self,\n embed_dims,\n num_heads,\n input_dims=None,\n attn_drop=0.,\n proj_drop=0.,\n dropout_layer=dict(type='Dropout', drop_prob=0.),\n qkv_bias=True,\n att_grad=True,\n qk_scale=None,\n proj_bias=True,\n v_shortcut=False,\n init_cfg=None):\n super(MultiheadAttention, self).__init__(init_cfg=init_cfg)\n\n self.input_dims = input_dims or embed_dims\n self.embed_dims = embed_dims\n self.num_heads = num_heads\n self.v_shortcut = v_shortcut\n\n self.head_dims = embed_dims // num_heads\n self.scale = qk_scale or self.head_dims**-0.5\n\n qkv = nn.Linear(self.input_dims, embed_dims * 3, bias=qkv_bias)\n for param in qkv.parameters():\n param.requires_grad=att_grad\n self.qkv = qkv\n self.attn_drop = nn.Dropout(attn_drop)\n proj = nn.Linear(embed_dims, embed_dims, bias=proj_bias)\n for param in proj.parameters():\n param.requires_grad=att_grad\n self.proj = proj\n self.proj_drop = nn.Dropout(proj_drop)\n\n self.out_drop = DROPOUT_LAYERS.build(dropout_layer)\n\n def forward(self, x):\n B, N, _ = x.shape\n qkv = self.qkv(x).reshape(B, N, 3, self.num_heads,\n self.head_dims).permute(2, 0, 3, 1, 4)\n q, k, v = qkv[0], qkv[1], qkv[2]\n\n attn = (q @ k.transpose(-2, -1)) * self.scale\n attn = attn.softmax(dim=-1)\n attn = self.attn_drop(attn)\n\n x = (attn @ v).transpose(1, 2).reshape(B, N, self.embed_dims)\n x = self.proj(x)\n x = self.out_drop(self.proj_drop(x))\n\n if self.v_shortcut:\n x = v.squeeze(1) + x\n return x\n" ]
[ [ "torch.nn.Linear", "torch.zeros", "torch.nn.Dropout", "torch.roll", "torch.arange", "torch.nn.Softmax", "torch.nn.functional.pad" ] ]
ZM-Zhou/SMDE-Pytorch
[ "7a8eb3400b450a492df05cd4724dfd259c3a733a" ]
[ "datasets/utils/export_gt_depth.py" ]
[ "from __future__ import absolute_import, division, print_function\n\nimport os\n\nimport argparse\nimport numpy as np\nimport PIL.Image as pil\n\nimport os\nimport sys\nsys.path.append(os.getcwd())\nfrom datasets.utils.data_reader import generate_depth_map\n\n\ndef export_gt_depths_kitti():\n\n parser = argparse.ArgumentParser(description='export_gt_depth')\n\n parser.add_argument('--data_path',\n type=str,\n help='path to the root of the KITTI data',\n required=True)\n opt = parser.parse_args()\n\n split_folder = os.path.join(os.getcwd(), \"data_splits\", \"kitti\")\n\n with open(os.path.join(split_folder, \"test_list.txt\"), \"r\") as f:\n lines = f.readlines()\n\n print(\"Exporting ground truth depths for {}\".format(\"eigen\"))\n\n gt_depths = []\n for line in lines:\n\n folder, frame_id, _ = line.split()\n frame_id = int(frame_id)\n\n \n calib_dir = os.path.join(opt.data_path, folder.split(\"/\")[0])\n velo_filename = os.path.join(opt.data_path, folder,\n \"velodyne_points/data\", \"{:010d}.bin\".format(frame_id))\n gt_depth = generate_depth_map(calib_dir, velo_filename, 2, True)\n\n gt_depths.append(gt_depth.astype(np.float32))\n\n output_path = os.path.join(opt.data_path, \"gt_depths.npz\")\n\n print(\"Saving to {}\".format(\"eigen\"))\n\n np.savez_compressed(output_path, data=np.array(gt_depths))\n\n\nif __name__ == \"__main__\":\n export_gt_depths_kitti()" ]
[ [ "numpy.array" ] ]
joshuamosesb/gramex
[ "e416cb609698b5941a18b06743c853dee50e0500" ]
[ "tests/test_logviewer.py" ]
[ "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport os.path\nimport pandas as pd\nimport gramex.cache\nfrom glob import glob\nimport sqlalchemy as sa\nfrom nose.tools import eq_, ok_\nfrom nose.tools import assert_almost_equals as aae\nfrom pandas.testing import assert_frame_equal as afe\nfrom gramex import conf\nfrom gramex.services import info\nfrom gramex.apps.logviewer import logviewer\nfrom . import TestGramex\n\n\nclass TestLogViewer(TestGramex):\n\n @staticmethod\n def get_keywith(config, key):\n item = next((v for k, v in config.items()\n if k.startswith(key)), None)\n return item\n\n @classmethod\n def setUpClass(cls):\n cls.log_file = conf.log.handlers.requests.filename\n cls.columns = conf.log.handlers.requests['keys']\n cls.dirpath = os.path.dirname(cls.log_file)\n cls.dbpath = os.path.join(cls.dirpath, 'logviewer.db')\n cls.queryconf = cls.get_keywith(conf.url, 'apps/logviewer/query-')\n schd = cls.get_keywith(info.schedule, 'apps/logviewer-')\n # check schedule is present in config\n ok_(schd is not None)\n # Remove logviewer.db before running scheduler\n os.remove(cls.dbpath)\n # run logviewer scheduler once\n schd.run()\n # df with raw logs\n df = pd.concat([\n gramex.cache.open(f, 'csv', names=cls.columns).fillna('-')\n for f in glob(cls.log_file + '*')\n ], ignore_index=True)\n cls.df = logviewer.prepare_logs(df)\n spec = cls.get_keywith(conf.schedule, 'apps/logviewer-')\n for transform_type in ['transforms', 'post_transforms']:\n for transform in spec.kwargs.get(transform_type, []):\n logviewer.apply_transform(cls.df, transform)\n\n def test_setup(self):\n # check if db exists\n ok_(os.path.isfile(self.dbpath))\n engine = sa.create_engine('sqlite:///{}'.format(self.dbpath))\n # check if db has 3 tables\n eq_(engine.table_names(), ['aggD', 'aggM', 'aggW'])\n\n def test_endpoints(self):\n self.check('/logviewer/')\n self.check('/logviewer/query/', code=404)\n # check query endpoints\n spec = self.get_keywith(conf.url, 'apps/logviewer/query-')\n base = '/logviewer/query/aggD'\n df = self.df\n df_user1 = df['user.id_1'].eq(1)\n df_uri1 = df['uri_1'].eq(1)\n # check filters\n for col in ['status', 'ip']:\n eq_(self.get('{}/filter{}/'.format(base, col)).json(),\n [{col: x} for x in sorted(df[col].unique())]\n )\n eq_(self.get('{}/filter{}/'.format(base, 'users')).json(),\n [{'user.id': x} for x in\n sorted(df[df_user1]['user.id'].unique())]\n )\n eq_(self.get('{}/filter{}/'.format(base, 'uri')).json(),\n (df[df_uri1]['uri'].value_counts()\n .astype(int)\n .rename_axis('uri').reset_index(name='views')\n .sort_values(by=['views', 'uri'], ascending=[False, True])[:100]\n .to_dict('r'))\n )\n # check KPIs\n eq_(self.get('{}/kpi-{}/'.format(base, 'pageviews')).json(),\n [{'value': len(df[df_uri1].index)}]\n )\n eq_(self.get('{}/kpi-{}/'.format(base, 'sessions')).json(),\n [{'value': df[df_user1]['new_session'].sum()}]\n )\n eq_(self.get('{}/kpi-{}/'.format(base, 'users')).json(),\n [{'value': df[df_user1]['user.id'].nunique()}]\n )\n eq_(self.get('{}/kpi-{}/'.format(base, 'urls')).json(),\n [{'value': df[df_uri1]['uri'].nunique()}]\n )\n r = self.get('{}/kpi-{}/'.format(base, 'avgtimespent')).json()\n aae(r[0]['value'],\n df[df_user1]['session_time'].sum() / df[df_user1]['new_session'].sum(),\n 4)\n r = self.get('{}/kpi-{}/'.format(base, 'avgloadtime')).json()\n aae(r[0]['value'], df['duration'].mean(), 4)\n # check top10\n topten = [{'col': 'user.id', 'url': 'users', 'values': 'views', 'flag': True},\n {'col': 'ip', 'url': 'ip', 'values': 'requests'},\n {'col': 'status', 'url': 'status', 'values': 'requests'},\n {'col': 'uri', 'url': 'uri', 'values': 'views', 'flag': True}]\n for top in topten:\n cond = (df[top['col'] + '_1'].eq(1)\n if top.get('flag') else slice(None))\n eq_(self.get('{}/topten{}/'.format(base, top['url'])).json(),\n (df[cond][top['col']].value_counts()\n .astype(int)\n .rename_axis(top['col']).reset_index(name=top['values'])\n .sort_values(by=[top['values'], top['col']],\n ascending=[False, True])[:10]\n .to_dict('r'))\n )\n # check trend\n dff = logviewer.pdagg(df[df_uri1],\n [{'key': 'time', 'freq': 'D'}],\n {'duration': ['count']})\n dff['time'] = dff['time'].dt.strftime('%Y-%m-%d 00:00:00')\n dff['pageviews'] = dff['duration_count'].astype(int)\n dff = dff[dff['pageviews'].ne(0)]\n eq_(self.get('{}/{}/'.format(base, 'pageviewstrend')).json(),\n dff.drop('duration_count', 1).to_dict('r')\n )\n dff = logviewer.pdagg(df[df_user1],\n [{'key': 'time', 'freq': 'D'}],\n {'new_session': ['sum']})\n dff['time'] = dff['time'].dt.strftime('%Y-%m-%d 00:00:00')\n dff['sessions'] = dff['new_session_sum'].astype(int)\n dff = dff[dff['sessions'].ne(0)]\n eq_(self.get('{}/{}/'.format(base, 'sessionstrend')).json(),\n dff.drop('new_session_sum', 1).query('sessions != 0').to_dict('r')\n )\n # TODO trend queries\n for q in spec.kwargs.kwargs.queries.keys():\n if q.endswith('trend'):\n self.check('{}/{}/'.format(base, q))\n\n def test_pdagg(self):\n dfe = (self.df.groupby([pd.Grouper(key='time', freq='D')])\n .agg({'duration': ['count']}).reset_index())\n dfe.columns = ['time', 'duration_count']\n afe(logviewer.pdagg(\n self.df,\n [{'key': 'time', 'freq': 'D'}],\n {'duration': ['count']}),\n dfe\n )\n\n def test_prepare_where(self):\n eq_(logviewer.prepare_where(\n 'SELECT * FROM tb', {'col1>': ['10']}, ['col1']),\n 'WHERE \"col1\" > \"10\"')\n eq_(logviewer.prepare_where(\n 'SELECT * FROM tb WHERE col2 > 1', {'col1>': ['10']}, ['col1']),\n 'AND \"col1\" > \"10\"')\n eq_(logviewer.prepare_where(\n '', {'col1>': ['10']}, ['col1']),\n 'WHERE \"col1\" > \"10\"')\n\n def test_apply_transform(self):\n ok_('__temp__' not in self.df)\n spec = {\n 'type': 'derive',\n 'expr': {'col': 'user.id', 'op': 'NOTIN', 'value': ['-', 'dev']},\n 'as': '__temp__'\n }\n logviewer.apply_transform(self.df, spec)\n ok_('__temp__' in self.df)\n self.df.drop('__temp__', 1)\n" ]
[ [ "pandas.Grouper" ] ]
YashBit/accelerate-skillDiscovery
[ "129a32c3d376eabb5d054dcd949c33aa686a97d4" ]
[ "library-algo/diayn-main/rlkit/torch/dqn/dqn_with_encoder.py" ]
[ "from collections import OrderedDict\n\nimport numpy as np\nimport torch\nimport torch.optim as optim\nfrom torch import nn as nn\n\nimport rlkit.torch.pytorch_util as ptu\nfrom rlkit.core.eval_util import create_stats_ordered_dict\nfrom rlkit.torch.torch_rl_algorithm import TorchTrainer\n\n\nclass DQNTrainer(TorchTrainer):\n def __init__(\n self,\n qf,\n target_qf,\n encoder,\n target_encoder,\n learning_rate=1e-3,\n soft_target_tau=1e-3,\n target_update_period=1,\n qf_criterion=None,\n do_target_update=True,\n discount=0.99,\n reward_scale=1.0,\n ):\n super().__init__()\n self.qf = qf\n self.target_qf = target_qf\n self.encoder = encoder\n self.target_encoder = target_encoder\n self.learning_rate = learning_rate\n self.soft_target_tau = soft_target_tau\n self.target_update_period = target_update_period\n self.qf_optimizer = optim.Adam(\n list(self.qf.parameters()) + list(self.encoder.parameters()),\n lr=self.learning_rate,\n )\n self.discount = discount\n self.reward_scale = reward_scale\n self.qf_criterion = qf_criterion or nn.MSELoss()\n self.eval_statistics = OrderedDict()\n self._n_train_steps_total = 0\n self._need_to_update_eval_statistics = True\n self.do_target_update = do_target_update\n\n # if not do_target_update:\n # ptu.copy_model_params_from_to(self.qf, self.target_qf)\n\n def train_from_torch(self, batch):\n rewards = batch['rewards'] * self.reward_scale\n terminals = batch['terminals']\n obs = batch['observations']\n actions = batch['actions']\n next_obs = batch['next_observations']\n\n \"\"\"\n Compute loss\n \"\"\"\n if not self.do_target_update:\n target_q_values = self.qf(self.encoder(next_obs)).detach().max(\n 1, keepdim=True\n )[0]\n else:\n target_q_values = self.target_qf(self.target_encoder(next_obs)).detach().max(\n 1, keepdim=True\n )[0]\n y_target = rewards + (1. - terminals) * self.discount * target_q_values\n y_target = y_target.detach()\n # actions is a one-hot vector\n y_pred = torch.sum(self.qf(self.encoder(obs)) * actions, dim=1, keepdim=True)\n qf_loss = self.qf_criterion(y_pred, y_target)\n\n \"\"\"\n Soft target network updates\n \"\"\"\n self.qf_optimizer.zero_grad()\n qf_loss.backward()\n self.qf_optimizer.step()\n\n \"\"\"\n Soft Updates\n \"\"\"\n if self._n_train_steps_total % self.target_update_period == 0 and self.do_target_update:\n ptu.soft_update_from_to(\n self.qf, self.target_qf, self.soft_target_tau\n )\n ptu.soft_update_from_to(\n self.encoder, self.target_encoder, self.soft_target_tau\n )\n\n\n \"\"\"\n Save some statistics for eval using just one batch.\n \"\"\"\n if self._need_to_update_eval_statistics:\n self._need_to_update_eval_statistics = False\n self.eval_statistics['QF Loss'] = np.mean(ptu.get_numpy(qf_loss))\n self.eval_statistics.update(create_stats_ordered_dict(\n 'Y Predictions',\n ptu.get_numpy(y_pred),\n ))\n\n def get_diagnostics(self):\n return self.eval_statistics\n\n def end_epoch(self, epoch):\n self._need_to_update_eval_statistics = True\n\n @property\n def networks(self):\n return [\n self.qf,\n self.target_qf,\n self.encoder,\n self.target_encoder\n ]\n\n def get_snapshot(self):\n return dict(\n qf=self.qf,\n target_qf=self.target_qf,\n )\n" ]
[ [ "torch.nn.MSELoss" ] ]
atrettin/pisa
[ "9702ed946e3f669f1126ca4ffe96b49280a8ff12" ]
[ "pisa/utils/stats.py" ]
[ "\"\"\"\nStatistical functions\n\"\"\"\n\n\nfrom __future__ import absolute_import, division\n\nimport numpy as np\nfrom scipy.special import gammaln\nfrom uncertainties import unumpy as unp\n\nfrom pisa import FTYPE\nfrom pisa.utils.comparisons import FTYPE_PREC, isbarenumeric\nfrom pisa.utils.log import logging\nfrom pisa.utils import likelihood_functions\n\n__all__ = ['SMALL_POS', 'CHI2_METRICS', 'LLH_METRICS', 'ALL_METRICS',\n 'maperror_logmsg',\n 'chi2', 'llh', 'log_poisson', 'log_smear', 'conv_poisson',\n 'norm_conv_poisson', 'conv_llh', 'barlow_llh', 'mod_chi2', 'correct_chi2',\n 'mcllh_mean', 'mcllh_eff', 'signed_sqrt_mod_chi2', 'generalized_poisson_llh']\n\n__author__ = 'P. Eller, T. Ehrhardt, J.L. Lanfranchi, E. Bourbeau'\n\n__license__ = '''Copyright (c) 2014-2020, The IceCube Collaboration\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\nSMALL_POS = 1e-10 #if FTYPE == np.float64 else FTYPE_PREC\n\"\"\"A small positive number with which to replace numbers smaller than it\"\"\"\n\nCHI2_METRICS = ['chi2', 'mod_chi2', 'correct_chi2']\n\"\"\"Metrics defined that result in measures of chi squared\"\"\"\n\nLLH_METRICS = ['llh', 'conv_llh', 'barlow_llh', 'mcllh_mean', \n'mcllh_eff', 'generalized_poisson_llh']\n\"\"\"Metrics defined that result in measures of log likelihood\"\"\"\n\nALL_METRICS = LLH_METRICS + CHI2_METRICS\n\"\"\"All metrics defined\"\"\"\n\nMETRICS_TO_MAXIMIZE = LLH_METRICS\n\"\"\"Metrics that must be maximized to obtain a better fit\"\"\"\n\nMETRICS_TO_MINIMIZE = CHI2_METRICS\n\"\"\"Metrics that must be minimized to obtain a better fit\"\"\"\n\n\n# TODO(philippeller):\n# * unit tests to ensure these don't break\n\ndef it_got_better(new_metric_val, old_metric_val, metric):\n \"\"\"Compare metric values and report whether improvement found.\n \"\"\"\n to_maximize = is_metric_to_maximize(metric)\n if to_maximize:\n got_better = new_metric_val > old_metric_val\n else:\n got_better = new_metric_val < old_metric_val\n return got_better\n\ndef is_metric_to_maximize(metric):\n \"\"\"Check whether the resulting metric has to be maximized or minimized.\n \"\"\"\n if isinstance(metric, str):\n metric = [metric]\n if all(m in METRICS_TO_MAXIMIZE for m in metric):\n return True\n if all(m in METRICS_TO_MINIMIZE for m in metric):\n return False\n raise ValueError('Defined metrics %s are not compatible' % metric)\n\ndef maperror_logmsg(m):\n \"\"\"Create message with thorough info about a map for logging purposes\"\"\"\n with np.errstate(invalid='ignore'):\n msg = ''\n msg += ' min val : %s\\n' %np.nanmin(m)\n msg += ' max val : %s\\n' %np.nanmax(m)\n msg += ' mean val: %s\\n' %np.nanmean(m)\n msg += ' num < 0 : %s\\n' %np.sum(m < 0)\n msg += ' num == 0: %s\\n' %np.sum(m == 0)\n msg += ' num > 0 : %s\\n' %np.sum(m > 0)\n msg += ' num nan : %s\\n' %np.sum(np.isnan(m))\n return msg\n\n\ndef chi2(actual_values, expected_values):\n \"\"\"Compute the chi-square between each value in `actual_values` and\n `expected_values`.\n\n Parameters\n ----------\n actual_values, expected_values : numpy.ndarrays of same shape\n\n Returns\n -------\n chi2 : numpy.ndarray of same shape as inputs\n chi-squared values corresponding to each pair of elements in the inputs\n\n Notes\n -----\n * Uncertainties are not propagated through this calculation.\n * Values in expectation are clipped to the range [SMALL_POS, inf] prior to\n the calculation to avoid infinities due to the divide function.\n * actual_values are allowed to be = 0, since they don't com up in the denominator\n \"\"\"\n if actual_values.shape != expected_values.shape:\n raise ValueError(\n 'Shape mismatch: actual_values.shape = %s,'\n ' expected_values.shape = %s'\n % (actual_values.shape, expected_values.shape)\n )\n\n # Convert to simple numpy arrays containing floats\n if not isbarenumeric(actual_values):\n actual_values = unp.nominal_values(actual_values)\n if not isbarenumeric(expected_values):\n expected_values = unp.nominal_values(expected_values)\n\n with np.errstate(invalid='ignore'):\n # Mask off any nan expected values (these are assumed to be ok)\n actual_values = np.ma.masked_invalid(actual_values)\n expected_values = np.ma.masked_invalid(expected_values)\n\n # TODO: this check (and the same for `actual_values`) should probably\n # be done elsewhere... maybe?\n if np.any(actual_values < 0):\n msg = ('`actual_values` must all be >= 0...\\n'\n + maperror_logmsg(actual_values))\n raise ValueError(msg)\n\n if np.any(expected_values < 0):\n msg = ('`expected_values` must all be >= 0...\\n'\n + maperror_logmsg(expected_values))\n raise ValueError(msg)\n\n # TODO: Is this okay to do? Mathematically suspect at best, and can\n # still destroy a minimizer's hopes and dreams...\n\n # Replace 0's with small positive numbers to avoid inf in division\n np.clip(expected_values, a_min=SMALL_POS, a_max=np.inf,\n out=expected_values)\n\n\n delta = actual_values - expected_values\n\n if np.all(np.abs(delta) < 5*FTYPE_PREC):\n return np.zeros_like(delta, dtype=FTYPE)\n\n chi2_val = np.square(delta) / expected_values\n assert np.all(chi2_val >= 0), str(chi2_val[chi2_val < 0])\n return chi2_val\n\n\ndef llh(actual_values, expected_values):\n \"\"\"Compute the log-likelihoods (llh) that each count in `actual_values`\n came from the the corresponding expected value in `expected_values`.\n\n Parameters\n ----------\n actual_values, expected_values : numpy.ndarrays of same shape\n\n Returns\n -------\n llh : numpy.ndarray of same shape as the inputs\n llh corresponding to each pair of elements in `actual_values` and\n `expected_values`.\n\n Notes\n -----\n * Uncertainties are not propagated through this calculation.\n * Values in `expected_values` are clipped to the range [SMALL_POS, inf]\n prior to the calculation to avoid infinities due to the log function.\n\n \"\"\"\n assert actual_values.shape == expected_values.shape\n\n # Convert to simple numpy arrays containing floats\n if not isbarenumeric(actual_values):\n actual_values = unp.nominal_values(actual_values)\n if not isbarenumeric(expected_values):\n expected_values = unp.nominal_values(expected_values)\n\n with np.errstate(invalid='ignore'):\n # Mask off any nan expected values (these are assumed to be ok)\n actual_values = np.ma.masked_invalid(actual_values)\n expected_values = np.ma.masked_invalid(expected_values)\n\n\n # TODO: How should we handle nan / masked values in the \"data\"\n # (actual_values) distribution? How about negative numbers?\n\n # Make sure actual values (aka \"data\") are valid -- no infs, no nans,\n # etc.\n if np.any((actual_values < 0) | ~np.isfinite(actual_values)):\n msg = ('`actual_values` must be >= 0 and neither inf nor nan...\\n'\n + maperror_logmsg(actual_values))\n raise ValueError(msg)\n\n # Check that new array contains all valid entries\n if np.any(expected_values < 0.0):\n msg = ('`expected_values` must all be >= 0...\\n'\n + maperror_logmsg(expected_values))\n raise ValueError(msg)\n\n # Replace 0's with small positive numbers to avoid inf in log\n np.clip(expected_values, a_min=SMALL_POS, a_max=np.inf,\n out=expected_values)\n\n #\n # natural logarith m of the Poisson probability\n # (uses Stirling's approximation to estimate ln(k!) ~ kln(k)-k)\n #\n llh_val = actual_values*np.log(expected_values) - expected_values\n llh_val -= actual_values*np.log(actual_values) - actual_values\n\n return llh_val\n\ndef mcllh_mean(actual_values, expected_values):\n \"\"\"Compute the log-likelihood (llh) based on LMean in table 2 - https://doi.org/10.1007/JHEP06(2019)030\n accounting for finite MC statistics.\n This is the second most recommended likelihood in the paper.\n\n Parameters\n ----------\n actual_values, expected_values : numpy.ndarrays of same shape\n\n Returns\n -------\n llh : numpy.ndarray of same shape as the inputs\n llh corresponding to each pair of elements in `actual_values` and\n `expected_values`.\n\n Notes\n -----\n *\n \"\"\"\n assert actual_values.shape == expected_values.shape\n\n # Convert to simple numpy arrays containing floats\n actual_values = unp.nominal_values(actual_values).ravel()\n sigma = unp.std_devs(expected_values).ravel()\n expected_values = unp.nominal_values(expected_values).ravel()\n\n with np.errstate(invalid='ignore'):\n # Mask off any nan expected values (these are assumed to be ok)\n actual_values = np.ma.masked_invalid(actual_values)\n expected_values = np.ma.masked_invalid(expected_values)\n\n\n # TODO: How should we handle nan / masked values in the \"data\"\n # (actual_values) distribution? How about negative numbers?\n\n # Make sure actual values (aka \"data\") are valid -- no infs, no nans,\n # etc.\n if np.any((actual_values < 0) | ~np.isfinite(actual_values)):\n msg = ('`actual_values` must be >= 0 and neither inf nor nan...\\n'\n + maperror_logmsg(actual_values))\n raise ValueError(msg)\n\n # Check that new array contains all valid entries\n if np.any(expected_values < 0.0):\n msg = ('`expected_values` must all be >= 0...\\n'\n + maperror_logmsg(expected_values))\n raise ValueError(msg)\n\n # Replace 0's with small positive numbers to avoid inf in log\n np.clip(expected_values, a_min=SMALL_POS, a_max=np.inf,\n out=expected_values)\n\n llh_val = likelihood_functions.poisson_gamma(\n data=actual_values, sum_w=expected_values, sum_w2=sigma**2, a=0, b=0\n )\n\n return llh_val\n\n\ndef mcllh_eff(actual_values, expected_values):\n \"\"\"Compute the log-likelihood (llh) based on eq. 3.16 - https://doi.org/10.1007/JHEP06(2019)030\n accounting for finite MC statistics.\n This is the most recommended likelihood in the paper.\n\n Parameters\n ----------\n actual_values, expected_values : numpy.ndarrays of same shape\n\n Returns\n -------\n llh : numpy.ndarray of same shape as the inputs\n llh corresponding to each pair of elements in `actual_values` and\n `expected_values`.\n\n Notes\n -----\n *\n \"\"\"\n assert actual_values.shape == expected_values.shape\n\n # Convert to simple numpy arrays containing floats\n actual_values = unp.nominal_values(actual_values).ravel()\n sigma = unp.std_devs(expected_values).ravel()\n expected_values = unp.nominal_values(expected_values).ravel()\n\n with np.errstate(invalid='ignore'):\n # Mask off any nan expected values (these are assumed to be ok)\n actual_values = np.ma.masked_invalid(actual_values)\n expected_values = np.ma.masked_invalid(expected_values)\n\n\n # TODO: How should we handle nan / masked values in the \"data\"\n # (actual_values) distribution? How about negative numbers?\n\n # Make sure actual values (aka \"data\") are valid -- no infs, no nans,\n # etc.\n if np.any((actual_values < 0) | ~np.isfinite(actual_values)):\n msg = ('`actual_values` must be >= 0 and neither inf nor nan...\\n'\n + maperror_logmsg(actual_values))\n raise ValueError(msg)\n\n # Check that new array contains all valid entries\n if np.any(expected_values < 0.0):\n msg = ('`expected_values` must all be >= 0...\\n'\n + maperror_logmsg(expected_values))\n raise ValueError(msg)\n\n # Replace 0's with small positive numbers to avoid inf in log\n np.clip(expected_values, a_min=SMALL_POS, a_max=np.inf,\n out=expected_values)\n\n llh_val = likelihood_functions.poisson_gamma(\n data=actual_values, sum_w=expected_values, sum_w2=sigma**2, a=1, b=0\n )\n return llh_val\n\n\n\ndef log_poisson(k, l):\n r\"\"\"Calculate the log of a poisson pdf\n\n .. math::\n p(k,l) = \\log\\left( l^k \\cdot e^{-l}/k! \\right)\n\n Parameters\n ----------\n k : float\n l : float\n\n Returns\n -------\n\n log of poisson\n\n \"\"\"\n return k*np.log(l) -l - gammaln(k+1)\n\n\ndef log_smear(x, sigma):\n r\"\"\"Calculate the log of a normal pdf\n\n .. math::\n p(x, \\sigma) = \\log\\left( (\\sigma \\sqrt{2\\pi})^{-1} \\exp( -x^2 / 2\\sigma^2 ) \\right)\n\n Parameters\n ----------\n x : float\n sigma : float\n\n Returns\n -------\n log of gaussian\n\n \"\"\"\n return (\n -np.log(sigma) - 0.5*np.log(2*np.pi) - x**2 / (2*sigma**2)\n )\n\n\ndef conv_poisson(k, l, s, nsigma=3, steps=50):\n r\"\"\"Poisson pdf\n\n .. math::\n p(k,l) = l^k \\cdot e^{-l}/k!\n\n Parameters\n ----------\n k : float\n l : float\n s : float\n sigma for smearing term (= the uncertainty to be accounted for)\n nsigma : int\n The ange in sigmas over which to do the convolution, 3 sigmas is > 99%,\n so should be enough\n steps : int\n Number of steps to do the intergration in (actual steps are 2*steps + 1,\n so this is the steps to each side of the gaussian smearing term)\n\n Returns\n -------\n float\n convoluted poissson likelihood\n\n \"\"\"\n # Replace 0's with small positive numbers to avoid inf in log\n l = max(SMALL_POS, l)\n st = 2*(steps + 1)\n conv_x = np.linspace(-nsigma*s, +nsigma*s, st)[:-1]+nsigma*s/(st-1.)\n conv_y = log_smear(conv_x, s)\n f_x = conv_x + l\n #f_x = conv_x + k\n # Avoid zero values for lambda\n idx = np.argmax(f_x > 0)\n f_y = log_poisson(k, f_x[idx:])\n #f_y = log_poisson(f_x[idx:], l)\n if np.isnan(f_y).any():\n logging.error('`NaN values`:')\n logging.error('idx = %d', idx)\n logging.error('s = %s', s)\n logging.error('l = %s', l)\n logging.error('f_x = %s', f_x)\n logging.error('f_y = %s', f_y)\n f_y = np.nan_to_num(f_y)\n conv = np.exp(conv_y[idx:] + f_y)\n norm = np.sum(np.exp(conv_y))\n return conv.sum()/norm\n\n\ndef norm_conv_poisson(k, l, s, nsigma=3, steps=50):\n \"\"\"Convoluted poisson likelihood normalized so that the value at k=l\n (asimov) does not change\n\n Parameters\n ----------\n k : float\n l : float\n s : float\n sigma for smearing term (= the uncertainty to be accounted for)\n nsigma : int\n The range in sigmas over which to do the convolution, 3 sigmas is >\n 99%, so should be enough\n steps : int\n Number of steps to do the intergration in (actual steps are 2*steps + 1,\n so this is the steps to each side of the gaussian smearing term)\n\n Returns\n -------\n likelihood\n Convoluted poisson likelihood normalized so that the value at k=l\n (asimov) does not change\n\n \"\"\"\n cp = conv_poisson(k, l, s, nsigma=nsigma, steps=steps)\n n1 = np.exp(log_poisson(l, l))\n n2 = conv_poisson(l, l, s, nsigma=nsigma, steps=steps)\n return cp*n1/n2\n\n\ndef conv_llh(actual_values, expected_values):\n \"\"\"Compute the convolution llh using the uncertainty on the expected values\n to smear out the poisson PDFs\n\n Parameters\n ----------\n actual_values, expected_values : numpy.ndarrays of same shape\n\n Returns\n -------\n total log of convoluted poisson likelihood\n\n \"\"\"\n actual_values = unp.nominal_values(actual_values).ravel()\n sigma = unp.std_devs(expected_values).ravel()\n expected_values = unp.nominal_values(expected_values).ravel()\n triplets = np.array([actual_values, expected_values, sigma]).T\n norm_triplets = np.array([actual_values, actual_values, sigma]).T\n total = 0\n for i in range(len(triplets)):\n total += np.log(max(SMALL_POS, norm_conv_poisson(*triplets[i]))) # FIXME? (cf. pylint)\n total -= np.log(max(SMALL_POS, norm_conv_poisson(*norm_triplets[i]))) # FIXME? (cf. pylint)\n return total\n\ndef barlow_llh(actual_values, expected_values):\n \"\"\"Compute the Barlow LLH taking into account finite statistics.\n The likelihood is described in this paper: https://doi.org/10.1016/0010-4655(93)90005-W\n Parameters\n ----------\n actual_values, expected_values : numpy.ndarrays of same shape\n\n Returns\n -------\n barlow_llh: numpy.ndarray\n\n \"\"\"\n\n actual_values = unp.nominal_values(actual_values).ravel()\n sigmas = unp.std_devs(expected_values).ravel()\n expected_values = unp.nominal_values(expected_values).ravel()\n\n with np.errstate(invalid='ignore'):\n # Mask off any nan expected values (these are assumed to be ok)\n actual_values = np.ma.masked_invalid(actual_values)\n expected_values = np.ma.masked_invalid(expected_values)\n\n # Check that new array contains all valid entries\n if np.any(actual_values < 0):\n msg = ('`actual_values` must all be >= 0...\\n'\n + maperror_logmsg(actual_values))\n raise ValueError(msg)\n\n # TODO: How should we handle nan / masked values in the \"data\"\n # (actual_values) distribution? How about negative numbers?\n\n # Make sure actual values (aka \"data\") are valid -- no infs, no nans,\n # etc.\n if np.any((actual_values < 0) | ~np.isfinite(actual_values)):\n msg = ('`actual_values` must be >= 0 and neither inf nor nan...\\n'\n + maperror_logmsg(actual_values))\n raise ValueError(msg)\n\n # Check that new array contains all valid entries\n if np.any(expected_values < 0.0):\n msg = ('`expected_values` must all be >= 0...\\n'\n + maperror_logmsg(expected_values))\n raise ValueError(msg)\n\n # TODO(tahmid): Run checks in case expected_values and/or corresponding sigma == 0\n # and handle these appropriately. If sigma/ev == 0 the code below will fail.\n unweighted = np.array([(ev/s)**2 for ev, s in zip(expected_values, sigmas)])\n weights = np.array([s**2/ev for ev, s in zip(expected_values, sigmas)])\n\n llh_val = likelihood_functions.barlowLLH(actual_values, unweighted, weights)\n return llh_val\n\ndef mod_chi2(actual_values, expected_values):\n \"\"\"Compute the chi-square value taking into account uncertainty terms\n (incl. e.g. finite stats)\n\n Parameters\n ----------\n actual_values, expected_values : numpy.ndarrays of same shape\n\n Returns\n -------\n m_chi2 : numpy.ndarray of same shape as inputs\n Modified chi-squared values corresponding to each pair of elements in\n the inputs\n\n \"\"\"\n # Replace 0's with small positive numbers to avoid inf in log\n np.clip(expected_values, a_min=SMALL_POS, a_max=np.inf,\n out=expected_values)\n actual_values = unp.nominal_values(actual_values).ravel()\n sigma = unp.std_devs(expected_values).ravel()\n expected_values = unp.nominal_values(expected_values).ravel()\n m_chi2 = (\n (actual_values - expected_values)**2 / (sigma**2 + expected_values)\n )\n return m_chi2\n\ndef correct_chi2(actual_values, expected_values):\n \"\"\"Compute the chi-square value taking into account uncertainty terms\n (incl. e.g. finite stats) and their changes\n\n Parameters\n ----------\n actual_values, expected_values : numpy.ndarrays of same shape\n\n Returns\n -------\n m_chi2 : numpy.ndarray of same shape as inputs\n Modified chi-squared values corresponding to each pair of elements in\n the inputs\n\n \"\"\"\n # Replace 0's with small positive numbers to avoid inf in log\n np.clip(expected_values, a_min=SMALL_POS, a_max=np.inf,\n out=expected_values)\n actual_values = unp.nominal_values(actual_values).ravel()\n sigma = unp.std_devs(expected_values).ravel()\n expected_values = unp.nominal_values(expected_values).ravel()\n total_variance = sigma**2 + expected_values\n m_chi2 = (\n (actual_values - expected_values)**2 / total_variance + np.log(total_variance)\n )\n return m_chi2\n\ndef signed_sqrt_mod_chi2(actual_values, expected_values):\n \"\"\"Compute a (signed) pull value taking into account uncertainty terms.\n\n Parameters\n ----------\n actual_values, expected_values : numpy.ndarrays of same shape\n\n Returns\n -------\n m_pull : numpy.ndarray of same shape as inputs\n Pull values corresponding to each pair of elements in\n the inputs\n\n \"\"\"\n # Replace 0's with small positive numbers to avoid inf in log\n np.clip(expected_values, a_min=SMALL_POS, a_max=np.inf,\n out=expected_values)\n actual_values = unp.nominal_values(actual_values).ravel()\n sigma = unp.std_devs(expected_values).ravel()\n expected_values = unp.nominal_values(expected_values).ravel()\n m_pull = (\n (actual_values - expected_values) / np.sqrt(sigma**2 + expected_values)\n )\n return m_pull\n \n#\n# Generalized Poisson-gamma llh from 1902.08831\n#\ndef generalized_poisson_llh(actual_values, expected_values=None, empty_bins=None):\n '''Compute the generalized Poisson likelihood as formulated in https://arxiv.org/abs/1902.08831\n\n\n Note that unlike the other likelihood functions, expected_values\n is expected to be a ditribution maker\n\n inputs:\n ------\n\n actual_values: flattened hist of a Map object\n\n expected_values: OrderedDict of MapSets\n\n empty_bins: None, list or np.ndarray (list the bin indices that are empty)\n\n returns:\n --------\n llh_per_bin : bin-wise llh values, in a numpy array\n\n '''\n from collections import OrderedDict\n\n \n assert isinstance(expected_values, OrderedDict), 'ERROR: expected_values must be an OrderedDict of MapSet objects'\n assert 'weights' in expected_values.keys(), 'ERROR: expected_values need a key named \"weights\"'\n assert 'llh_alphas' in expected_values.keys(), 'ERROR: expected_values need a key named \"llh_alphas\"'\n assert 'llh_betas' in expected_values.keys(), 'ERROR: expected_values need a key named \"llh_betas\"'\n\n num_bins = actual_values.flatten().shape[0]\n llh_per_bin = np.zeros(num_bins)\n actual_values = unp.nominal_values(actual_values).ravel()\n\n # If no empty bins are specified, we assume that all of them should be included\n if empty_bins is None:\n empty_bins = []\n\n for bin_i in range(num_bins):\n\n # TODO: sometimes the histogram spits out uncertainty objects, sometimes not. \n # Not sure why.\n data_count = actual_values.astype(np.int64)[bin_i]\n\n # Automatically add a huge number if a bin has non zero data count\n # but completely empty MC\n if bin_i in empty_bins:\n if data_count > 0:\n llh_per_bin[bin_i] = np.log(SMALL_POS)\n continue\n\n # Make sure that no weight sum is negative. Crash if there are\n weight_sum = np.array([m.hist.flatten()[bin_i] for m in expected_values['weights'].maps])\n if (weight_sum<0).sum()>0:\n logging.debug('\\n\\n\\n')\n logging.debug('weights that are causing problem: ')\n logging.debug(weight_sum[weight_sum<0])\n logging.debug((weight_sum<0).sum())\n logging.debug('\\n\\n\\n')\n assert np.all(weight_sum >= 0), 'ERROR: negative weights detected'\n\n #\n # If the number of MC events is high, compute a normal poisson probability\n #\n n_mc_events = np.array([m.hist.flatten()[bin_i] for m in expected_values['n_mc_events'].maps])\n if np.all(n_mc_events>100):\n\n logP = data_count*np.log(weight_sum.sum())-weight_sum.sum()-(data_count*np.log(data_count)-data_count)\n llh_per_bin[bin_i] = logP\n \n else:\n from pisa.utils.llh_defs.poisson import fast_pgmix\n\n alphas = np.array([m.hist.flatten()[bin_i] for m in expected_values['llh_alphas'].maps])\n betas = np.array([m.hist.flatten()[bin_i] for m in expected_values['llh_betas'].maps])\n\n # Remove the NaN's \n mask = np.isfinite(alphas)*np.isfinite(betas)\n\n # Check that the alpha and betas make sense\n assert np.all(alphas[mask] > 0), 'ERROR: detected alpha values <=0'\n assert np.all(betas[mask] > 0 ), 'ERROR: detected beta values <=0'\n\n\n llh_of_bin = fast_pgmix(data_count, alphas[mask], betas[mask])\n llh_per_bin[bin_i] = llh_of_bin\n\n return llh_per_bin\n \n\ndef approximate_poisson_normal(data_count, alphas=None, betas=None, use_c=False):\n '''\n Compute the likelihood of a marginalized poisson-gamma\n function, using a single normal distribution instead of\n the convolution of gamma function\n\n This formula can be used when the MC counts are really\n high, and where the gamma function throws infinite values\n\n '''\n from scipy.integrate import quad\n import numpy as np\n\n gamma_mean = np.sum(alphas/betas)\n gamma_sigma = np.sqrt(np.sum(alphas/betas**2.))\n\n #\n # Define integration range as +- 5 sigma\n #\n lower = max(0,gamma_mean-5*gamma_sigma)\n upper = gamma_mean+5*gamma_sigma\n\n #\n # integrate over the boundaries\n #\n if use_c:\n\n import os, ctypes\n import numpy as np\n from scipy import integrate, LowLevelCallable\n\n lib = ctypes.CDLL(os.path.abspath('/groups/icecube/bourdeet/pisa/pisa/utils/poisson_normal.so'))\n lib.approximate_gamma_poisson_integrand.restype = ctypes.c_double\n lib.approximate_gamma_poisson_integrand.argtypes = (ctypes.c_int, ctypes.POINTER(ctypes.c_double), ctypes.c_void_p)\n\n # Define the parameters\n params = (ctypes.c_double*3)()\n\n params[0] = data_count\n params[1] = gamma_mean\n params[2] = gamma_sigma\n\n user_data = ctypes.cast(params, ctypes.c_void_p)\n func = LowLevelCallable(lib.approximate_gamma_poisson_integrand, user_data)\n LH = quad(func, lower, upper)[0]\n #print('lower ',lower,' upper: ',upper,' LH: ',LH)\n else:\n\n LH = quad(approximate_poisson_normal_python, lower, upper, args=(data_count, gamma_mean, gamma_sigma))[0]\n #print('lower ',lower,' upper: ',upper,' data_count: ',data_count,' mean: ', gamma_mean, ' sigma: ',gamma_sigma, ' LH: ',LH)\n\n LH = max(SMALL_POS,LH) \n return np.log(LH)\n\n\n\ndef approximate_poisson_normal_python(lamb, k, A, B):\n\n from scipy.stats import norm\n \n normal_term = norm.pdf(lamb, loc=A, scale=B)\n normal_poisson = norm.pdf(k, loc=lamb, scale=np.sqrt(lamb))\n\n return normal_term*normal_poisson\n" ]
[ [ "numpy.exp", "numpy.nanmean", "numpy.zeros_like", "numpy.nan_to_num", "numpy.log", "numpy.nanmin", "numpy.argmax", "numpy.sqrt", "numpy.isfinite", "numpy.nanmax", "numpy.square", "numpy.array", "numpy.zeros", "numpy.ma.masked_invalid", "numpy.clip", "scipy.integrate.quad", "scipy.special.gammaln", "numpy.isnan", "numpy.errstate", "numpy.sum", "scipy.LowLevelCallable", "numpy.any", "numpy.abs", "numpy.all", "numpy.linspace" ] ]
athenian-robotics/common-robotics-python
[ "a2ede8fb3072cf1baa53672f76081aa6bfde397f" ]
[ "arc852/contour_finder.py" ]
[ "import cv2\nimport numpy as np\n\nfrom arc852.constants import MINIMUM_PIXELS_DEFAULT, HSV_RANGE_DEFAULT\nfrom arc852.opencv_utils import contour_slope_degrees, contains_in_list, get_center\n\n\nclass ContourFinder(object):\n def __init__(self,\n bgr_color,\n hsv_range=HSV_RANGE_DEFAULT,\n minimum_pixels=MINIMUM_PIXELS_DEFAULT):\n self.__minimum_pixels = minimum_pixels\n\n # Convert into a tuple if it is a string\n bgr_tuple = eval(bgr_color if \"[\" in bgr_color else \"[{0}]\".format(bgr_color))\n bgr_img = np.uint8([[bgr_tuple]])\n hsv_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2HSV)\n hsv_value = hsv_img[0, 0, 0]\n\n self.__lower = np.array([hsv_value - hsv_range, 100, 100])\n self.__upper = np.array([hsv_value + hsv_range, 255, 255])\n\n def get_max_contours(self, image, lower=None, upper=None, count=1):\n # Convert from BGR to HSV colorspace\n hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n\n # Threshold the HSV image to get only target colors\n in_range_mask = cv2.inRange(hsv_image,\n lower if lower else self.__lower,\n upper if upper else self.__upper)\n\n # Bitwise-AND mask and original image\n in_range_result = cv2.bitwise_and(image, image, mask=in_range_mask)\n\n # Convert to grayscale\n grayscale = cv2.cvtColor(in_range_result, cv2.COLOR_BGR2GRAY)\n\n # cv2.imshow(\"HSV\", hsv_image)\n # cv2.imshow(\"Mask\", in_range_mask)\n # cv2.imshow(\"Res\", in_range_result)\n # cv2.imshow(\"Grayscale\", grayscale)\n\n # Return requested number of contours\n if True:\n contours = cv2.findContours(grayscale, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[1]\n # Return max contours that are not overlapping\n eligible = [c for c in contours if cv2.moments(c)[\"m00\"] >= self.__minimum_pixels]\n retval = []\n for val in sorted(eligible, key=lambda v: cv2.moments(v)[\"m00\"], reverse=True):\n if not contains_in_list(retval, get_center(val)):\n retval.append(val)\n if len(retval) == count:\n break\n return retval\n else:\n # Old way\n contours = cv2.findContours(grayscale, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[1]\n eligible = [c for c in contours if cv2.moments(c)[\"m00\"] >= self.__minimum_pixels]\n val = sorted(eligible, key=lambda v: cv2.moments(v)[\"m00\"], reverse=True)[:count]\n return val if val else None\n\n\n def get_max_vertical_contours(self, image, lower=None, upper=None, count=1):\n # Convert from BGR to HSV colorspace\n hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n\n # Threshold the HSV image to get only target colors\n in_range_mask = cv2.inRange(hsv_image,\n lower if lower else self.__lower,\n upper if upper else self.__upper)\n\n # Bitwise-AND mask and original image\n in_range_result = cv2.bitwise_and(image, image, mask=in_range_mask)\n\n # Convert to grayscale\n grayscale = cv2.cvtColor(in_range_result, cv2.COLOR_BGR2GRAY)\n\n # Get all contours\n contours = cv2.findContours(grayscale, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[1]\n\n # cv2.imshow(\"HSV\", hsv_image)\n # cv2.imshow(\"Mask\", in_range_mask)\n # cv2.imshow(\"Res\", in_range_result)\n # cv2.imshow(\"Grayscale\", grayscale)\n\n verticals = []\n for c in contours:\n if c is None:\n continue\n slope, degrees = contour_slope_degrees(c)\n if abs(degrees) < 70 or (slope is not None and abs(slope) < 20):\n # logger.info(\"Slope: {0}\".format(slope))\n # logger.info(\"Degrees: {0}\".format(degrees))\n continue\n verticals.append(c)\n\n # Return max verticval contours\n eligible = [c for c in verticals if cv2.moments(c)[\"m00\"] >= self.__minimum_pixels]\n val = sorted(eligible, key=lambda v: cv2.moments(v)[\"m00\"], reverse=True)[:count]\n return val if val else None\n" ]
[ [ "numpy.array", "numpy.uint8" ] ]
robhansen/advent2021
[ "390d49dd237200a8939b0d5486bbeb37c079807c" ]
[ "puzzle/day19.py" ]
[ "#!/usr/bin/env python3\r\n\r\nimport sys\r\nimport numpy\r\n\r\nif len(sys.argv) != 2:\r\n print(\"Help: {} <filename>\".format(sys.argv[0]))\r\n sys.exit(0)\r\n\r\nTRANSLATIONS = [(0,0,0),(0,0,1),(0,0,2),(0,0,3),(0,1,0),(0,1,1),(0,1,2),(0,1,3),(0,2,3),(0,3,3),\r\n (1,0,0),(1,0,1),(1,0,2),(1,0,3),(1,1,0),(1,1,1),(1,1,2),(1,1,3),(1,2,3),(1,3,3),\r\n (2,0,0),(2,0,1),(2,0,2),(2,0,3),(2,1,0),(2,1,1),(2,1,2),(2,1,3),(2,2,3),(2,3,3),\r\n (3,0,0),(3,0,1),(3,0,2),(3,0,3),(3,1,0),(3,1,1),(3,1,2),(3,1,3),(3,2,3),(3,3,3)]\r\nCOS = [1,0,-1,0]\r\nSIN = [0,1,0,-1]\r\ndef get_rotation_matrix(a,b,c): # rotation indexes (0,1,2,3) of z,y,x respectively\r\n matrix = numpy.zeros((3,3), dtype=int)\r\n numpy.put(matrix, range(9), [COS[a]*COS[b], (COS[a]*SIN[b]*SIN[c])-(SIN[a]*COS[c]), (COS[a]*SIN[b]*COS[c])+(SIN[a]*SIN[c]),\r\n SIN[a]*COS[b], (SIN[a]*SIN[b]*SIN[c])+(COS[a]*COS[c]), (SIN[a]*SIN[b]*COS[c])-(COS[a]*SIN[c]),\r\n 0-SIN[b], COS[b]*SIN[c], COS[b]*COS[c]])\r\n return matrix\r\n\r\nclass Scanner:\r\n def __init__(self):\r\n self.beacons = []\r\n self.vector_list_bidirectional = set()\r\n self.vector_list_lookup_table = {}\r\n self.canon = False\r\n self.origin = numpy.array([0,0,0])\r\n\r\n def add_beacon(self, beacon_string):\r\n self.beacons.append(numpy.array([int(x) for x in beacon_string.split(\",\")]))\r\n\r\n def calculate_canonical_vectors(self):\r\n self.canon = True\r\n for i in range(len(self.beacons)):\r\n for j in range(len(self.beacons)):\r\n if j!=i:\r\n vector = self.beacons[i]-self.beacons[j]\r\n self.vector_list_bidirectional.add(tuple(vector.tolist())) # convert to tuple so it's hashable\r\n self.vector_list_lookup_table[tuple(vector.tolist())] = (i,j)\r\n \r\n def get_vectors(self, rotation_indices):\r\n vector_list = set()\r\n for i in range(len(self.beacons)):\r\n for j in range(len(self.beacons)):\r\n if j>i: # for efficiency just get the ones in one direction, not their negatives too\r\n vector = numpy.array(self.beacons[i])-numpy.array(self.beacons[j])\r\n vector_list.add(tuple(numpy.dot(get_rotation_matrix(*rotation_indices), vector).tolist()))\r\n return vector_list\r\n\r\n def match_to(self, scanner, threshold):\r\n most_matches = [[], None]\r\n for t in TRANSLATIONS:\r\n inter = scanner.vector_list_bidirectional.intersection(self.get_vectors(t))\r\n if len(inter)>len(most_matches[0]):\r\n most_matches = [inter, t]\r\n if len(most_matches[0]) >= threshold: # match orientation and origin to that of scanner\r\n for i in range(len(self.beacons)):\r\n self.beacons[i] = numpy.dot(get_rotation_matrix(*most_matches[1]), self.beacons[i])\r\n self.calculate_canonical_vectors() # sets canon to True\r\n ref_vector = most_matches[0].pop()\r\n position_correction = scanner.beacons[scanner.vector_list_lookup_table[ref_vector][0]] - self.beacons[self.vector_list_lookup_table[ref_vector][0]]\r\n self.origin += position_correction\r\n for i in range(len(self.beacons)):\r\n self.beacons[i] += position_correction\r\n return True\r\n return False\r\n\r\nscanners = []\r\nwith open(sys.argv[1]) as file:\r\n for line in file:\r\n if len(line) > 4:\r\n if line[:3] == \"---\":\r\n scanners.append(Scanner())\r\n else:\r\n scanners[-1].add_beacon(line.rstrip())\r\n\r\nscanners[0].calculate_canonical_vectors() # use scanners[0] as the canonical orientation and position\r\ncanon_count = 1\r\nwhile canon_count < len(scanners):\r\n for i in range(len(scanners)):\r\n for j in range(1, len(scanners)):\r\n if scanners[i].canon and not scanners[j].canon:\r\n if scanners[j].match_to(scanners[i], 12):\r\n canon_count+=1\r\n print(\"Matched scanner {} to {} - {} canon of {}\".format(j,i,canon_count,len(scanners)))\r\n\r\nall_beacons = set()\r\nfor scanner in scanners:\r\n for beacon in scanner.beacons:\r\n all_beacons.add(tuple(beacon.tolist()))\r\nprint(\"{} unique beacons\".format(len(all_beacons)))\r\n\r\ndef manhatten_distance(a,b):\r\n return (abs(a[0]-b[0])+abs(a[1]-b[1])+abs(a[2]-b[2]))\r\n\r\nmax_distance = [0, None, None]\r\nfor i in range(len(scanners)):\r\n for j in range(len(scanners)):\r\n if manhatten_distance(scanners[i].origin, scanners[j].origin) > max_distance[0]:\r\n max_distance = [manhatten_distance(scanners[i].origin, scanners[j].origin), scanners[i].origin, scanners[j].origin]\r\nprint (\"Max Manhatten distance {} between {} and {}\".format(*max_distance))\r\n" ]
[ [ "numpy.array", "numpy.zeros" ] ]
mengesser/miricoord
[ "e4f7bef16f8a2e6f1d46c97a2b3d78cd50de7bec" ]
[ "miricoord/mrs/toolversions/mrs_pipetools_cdp6.py" ]
[ "#\n\"\"\"\nUseful python tools for working with the MIRI MRS.\nThis contains cdp6 specific code.\n\nThis version of the tools uses the JWST pipeline implementation\nof the distortion solution to do the transformations,\nand hooks into offline versions of the CRDS reference\nfiles contained within this github repository.\n\nConvert JWST v2,v3 locations (in arcsec) to MIRI MRS SCA x,y pixel locations.\nNote that the pipeline uses a 0-indexed detector pixel (1032x1024) convention while\nSIAF uses a 1-indexed detector pixel convention. The CDP files define\nthe origin such that (1,1) is the middle of the lower-left detector pixel\n(1032x1024),therefore also need to transform between this science frame and detector frame.\n\nAuthor: David R. Law ([email protected])\n\nREVISION HISTORY:\n10-Oct-2018 Written by David Law ([email protected])\n\"\"\"\n\nimport os as os\nimport numpy as np\nimport pdb as pdb\nfrom astropy.modeling import models\nfrom asdf import AsdfFile\nfrom jwst import datamodels\nfrom jwst.assign_wcs import miri\n\n#############################\n\n# Return the tools version\ndef version():\n return 'cdp6'\n\n#############################\n\n# Set the relevant CRDS distortion file based on channel (e.g., '1A')\ndef get_fitsreffile(channel):\n rootdir=os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n rootdir=os.path.join(rootdir,'data/crds/')\n\n wavefile=rootdir+'jwst_miri_wavelengthrange_0003.asdf'\n\n # Channel should be of the form (e.g.) '1A', '3C', etc\n # See https://jwst-crds.stsci.edu//display_result/52cef902-ad77-4792-9964-d26a0a8a96a8\n if ((channel is '1A')or(channel is '2A')):\n distfile=rootdir+'jwst_miri_distortion_0021.asdf'\n regfile=rootdir+'jwst_miri_regions_0016.asdf'\n specfile=rootdir+'jwst_miri_specwcs_0015.asdf'\n elif ((channel is '3A')or(channel is '4A')):\n distfile=rootdir+'jwst_miri_distortion_0024.asdf'\n regfile=rootdir+'jwst_miri_regions_0013.asdf'\n specfile=rootdir+'jwst_miri_specwcs_0017.asdf'\n elif ((channel is '1B')or(channel is '2B')):\n distfile=rootdir+'jwst_miri_distortion_0022.asdf'\n regfile=rootdir+'jwst_miri_regions_0015.asdf'\n specfile=rootdir+'jwst_miri_specwcs_0013.asdf'\n elif ((channel is '3B')or(channel is '4B')):\n distfile=rootdir+'jwst_miri_distortion_0026.asdf'\n regfile=rootdir+'jwst_miri_regions_0014.asdf'\n specfile=rootdir+'jwst_miri_specwcs_0018.asdf'\n elif ((channel is '1C')or(channel is '2C')):\n distfile=rootdir+'jwst_miri_distortion_0025.asdf'\n regfile=rootdir+'jwst_miri_regions_0018.asdf'\n specfile=rootdir+'jwst_miri_specwcs_0014.asdf'\n elif ((channel is '3C')or(channel is '4C')):\n distfile=rootdir+'jwst_miri_distortion_0027.asdf'\n regfile=rootdir+'jwst_miri_regions_0017.asdf'\n specfile=rootdir+'jwst_miri_specwcs_0016.asdf'\n else:\n print('Failure!')\n\n refs={'distortion': distfile, 'regions':regfile, 'specwcs':specfile, 'wavelengthrange':wavefile}\n return refs\n\n#############################\n\n# Convenience function to turn '1A' type name into '12' and 'SHORT' type names\ndef bandchan(channel):\n # Channel should be of the form (e.g.) '1A', '3C', etc\n if ((channel is '1A')or(channel is '2A')):\n newband='SHORT'\n newchannel='12'\n elif ((channel is '3A')or(channel is '4A')):\n newband='SHORT'\n newchannel='34'\n elif ((channel is '1B')or(channel is '2B')):\n newband='MEDIUM'\n newchannel='12'\n elif ((channel is '3B')or(channel is '4B')):\n newband='MEDIUM'\n newchannel='34'\n elif ((channel is '1C')or(channel is '2C')):\n newband='LONG'\n newchannel='12'\n elif ((channel is '3C')or(channel is '4C')):\n newband='LONG'\n newchannel='34'\n else:\n newband='FAIL'\n newchannel='FAIL'\n\n return newband,newchannel\n\n#############################\n\n# Convenience function to turn '12A' type name into '1A' and '2A' type names\ndef channel(detband):\n if (detband == '12A'):\n ch1='1A'\n ch2='2A'\n elif (detband == '12B'):\n ch1='1B'\n ch2='2B'\n elif (detband == '12C'):\n ch1='1C'\n ch2='2C'\n elif (detband == '34A'):\n ch1='3A'\n ch2='4A'\n elif (detband == '34B'):\n ch1='3B'\n ch2='4B'\n elif (detband == '34C'):\n ch1='3C'\n ch2='4C'\n else:\n ch1='FAIL'\n ch2='FAIL'\n\n return ch1,ch2\n\n#############################\n\n# Convenience function to return the rough middle wavelength of a given channel\n# Note that this ISNT exact, just some valid value\ndef midwave(channel):\n if (channel is '1A'):\n thewave=5.32\n elif (channel is '1B'):\n thewave=6.145\n elif (channel is '1C'):\n thewave=7.09\n elif (channel is '2A'):\n thewave=8.135\n elif (channel is '2B'):\n thewave=9.395\n elif (channel is '2C'):\n thewave=10.85\n elif (channel is '3A'):\n thewave=12.505\n elif (channel is '3B'):\n thewave=14.5\n elif (channel is '3C'):\n thewave=16.745\n elif (channel is '4A'):\n thewave=19.29\n elif (channel is '4B'):\n thewave=22.47\n elif (channel is '4C'):\n thewave=26.2\n\n return thewave\n\n#############################\n\n# Convenience function to return model distortion object\n# for the x,y to alpha,beta,lam transform\ndef xytoablmodel(channel,**kwargs):\n # Construct the reference data model in general JWST imager type\n input_model = datamodels.ImageModel()\n # Convert input of type '1A' into the band and channel that pipeline needs\n theband,thechan=bandchan(channel)\n # Set the filter in the data model meta header\n input_model.meta.instrument.band = theband\n input_model.meta.instrument.channel = thechan\n \n # If passed input refs keyword, unpack and use it\n if ('refs' in kwargs):\n therefs=kwargs['refs']\n # Otherwise use default reference files\n else:\n therefs=get_fitsreffile(channel)\n\n distortion = miri.detector_to_abl(input_model, therefs)\n # Return the distortion object that can then be queried\n return distortion\n\n#############################\n\n# Convenience function to return model distortion object\n# for the alpha,beta to v2,v3 transform\n\ndef abtov2v3model(channel,**kwargs):\n # Construct the reference data model in general JWST imager type\n input_model = datamodels.ImageModel()\n # Convert input of type '1A' into the band and channel that pipeline needs\n theband,thechan=bandchan(channel)\n # Set the filter in the data model meta header\n input_model.meta.instrument.band = theband\n input_model.meta.instrument.channel = thechan\n \n # If passed input refs keyword, unpack and use it\n if ('refs' in kwargs):\n therefs=kwargs['refs']\n # Otherwise use default reference files\n else:\n therefs=get_fitsreffile(channel)\n\n # The pipeline transform actually uses the triple\n # (alpha,beta,lambda) -> (v2,v3,lambda)\n basedistortion = miri.abl_to_v2v3l(input_model, therefs)\n distortion = basedistortion\n\n # Therefore we need to hack a reasonable wavelength onto our input, run transform,\n # then hack it back off again\n\n thewave=midwave(channel)\n # Duplicate the beta value at first, then replace with wavelength value\n map=models.Mapping((0,1,1)) | models.Identity(1) & models.Identity(1) & models.Const1D(thewave)\n map.inverse=models.Mapping((0,1),n_inputs=3)\n\n allmap= map | distortion | map.inverse\n allmap.inverse= map | distortion.inverse | map.inverse\n\n # Return the distortion object that can then be queried\n return allmap\n\n#############################\n\n# MRS test reference data\n# Convert all x,y values to 0-indexed\nmrs_ref_data = {\n '1A': {'x': np.array([28.310396, 475.02154, 493.9777, 41.282537, 58.998266])-1,\n 'y': np.array([512., 10, 100, 900, 1014])-1,\n 's': np.array([11, 1, 1, 21, 21]),\n 'alpha': np.array([0, -1.66946, 1.65180, -1.70573, 1.70244]),\n 'beta': np.array([0, -1.77210, -1.77210, 1.77210, 1.77210]),\n 'lam': np.array([5.34437, 4.86642, 4.95325, 5.65296, 5.74349]),\n 'xan': np.array([-8.39424, -8.41746, -8.36306, -8.42653, -8.37026]),\n 'yan': np.array([-2.48763, -2.52081, -2.51311, -2.46269, -2.45395]),\n },\n '1B': {'x': np.array([28.648221, 475.07259, 493.98157, 41.559386, 59.738296])-1,\n 'y': np.array([512., 10, 100, 900, 1014])-1,\n 's': np.array([11, 1, 1, 21, 21]),\n 'alpha': np.array([0., -1.70796, 1.60161, -1.70854, 1.78261]),\n 'beta': np.array([0., -1.77204, -1.77204, 1.77204, 1.77204]),\n 'lam': np.array([6.17572, 5.62345, 5.72380, 6.53231, 6.63698]),\n 'xan': np.array([-8.39426, -8.41808, -8.36368, -8.42682, -8.36899]),\n 'yan': np.array([-2.48492, -2.51808, -2.51040, -2.46001, -2.45126])\n },\n '1C': {'x': np.array([30.461871, 477.23742, 495.96228, 43.905314, 60.995683])-1,\n 'y': np.array([512., 10, 100, 900, 1014])-1,\n 's': np.array([11, 1, 1, 21, 21]),\n 'alpha': np.array([0., -1.60587, 1.67276, -1.60766, 1.68720]),\n 'beta': np.array([0., -1.77202, -1.77202, 1.77202, 1.77202]),\n 'lam': np.array([7.04951, 6.42424, 6.53753, 7.45360, 7.57167]),\n 'xan': np.array([-8.39357, -8.41570, -8.36165, -8.42457, -8.36996]),\n 'yan': np.array([-2.48987, -2.52271, -2.51525, -2.46467, -2.45649])\n },\n '2A': {'x': np.array([992.158, 545.38386, 525.76143, 969.29711, 944.19303])-1,\n 'y': np.array([512., 10, 100, 900, 1014])-1,\n 's': np.array([9, 1, 1, 17, 17]),\n 'alpha': np.array([0., -2.11250, 2.10676, -2.17239, 2.10447]),\n 'beta': np.array([0., -2.23775, -2.23775, 2.23775, 2.23775]),\n 'lam': np.array([8.20797, 7.52144, 7.64907, 8.68677, 8.83051]),\n 'xan': np.array([-8.39393, -8.42259, -8.35355, -8.43583, -8.36499]),\n 'yan': np.array([-2.48181, -2.52375, -2.51357, -2.44987, -2.44022])\n },\n '2B': {'x': np.array([988.39977, 541.23447, 521.60207, 964.91753, 940.10325])-1,\n 'y': np.array([512., 10, 100, 900, 1014])-1,\n 's': np.array([9, 1, 1, 17, 17]),\n 'alpha': np.array([0., -2.10593, 2.10015, -2.08817, 2.10422]),\n 'beta': np.array([0., -2.23781, -2.23781, 2.23781, 2.23781]),\n 'lam': np.array([9.44205, 8.65341, 8.79991, 9.99257, 10.15795]),\n 'xan': np.array([-8.39645, -8.42502, -8.35603, -8.43716, -8.36742]),\n 'yan': np.array([-2.47773, -2.51972, -2.50938, -2.44554, -2.43626])\n },\n '2C': {'x': np.array([990.89693, 543.82344, 524.34514, 967.98318, 942.77564])-1,\n 'y': np.array([512., 10, 100, 900, 1014])-1,\n 's': np.array([9, 1, 1, 17, 17]),\n 'alpha': np.array([0., -2.07490, 2.11234, -2.14704, 2.14196]),\n 'beta': np.array([0., -2.23778, -2.23778, 2.23778, 2.23778]),\n 'lam': np.array([10.90225, 9.99162, 10.16079, 11.53780, 11.72887]),\n 'xan': np.array([-8.39303, -8.42129, -8.35221, -8.43454, -8.36352]),\n 'yan': np.array([-2.47869, -2.52052, -2.51036, -2.44668, -2.43712])\n },\n '3A': {'x': np.array([574.80828, 1001.0602, 984.6387, 547.27479, 518.89992])-1,\n 'y': np.array([512., 10, 100, 900, 1014])-1,\n 's': np.array([8, 1, 1, 16, 16]),\n 'alpha': np.array([0., -2.86745, 3.20982, -3.01230, 2.96643]),\n 'beta': np.array([-0.19491, -2.92360, -2.92360, 2.92360, 2.92360]),\n 'lam': np.array([12.5335, 13.49968, 13.33846, 11.77148, 11.52350]),\n 'xan': np.array([-8.40590, -8.44849, -8.34906, -8.46070, -8.36174]),\n 'yan': np.array([-2.48992, -2.54104, -2.52854, -2.44547, -2.43112])\n },\n '3B': {'x': np.array([574.26012, 1001.7349, 985.30166, 548.016, 519.98])-1,\n 'y': np.array([512., 10., 100, 900, 1014])-1,\n 's': np.array([8, 1, 1, 16, 16]),\n 'alpha': np.array([0, -3.17728, 2.92434, -3.29402, 2.60797]),\n 'beta': np.array([-0.19491, -2.92360, -2.92360, 2.92360, 2.92360]),\n 'lam': np.array([14.53997, 15.66039, 15.47355, 13.65622, 13.36833]),\n 'xan': np.array([-8.40044, -8.44785, -8.34786, -8.46088, -8.36211]),\n 'yan': np.array([-2.48588, -2.53771, -2.52512, -2.44219, -2.42776])\n },\n '3C': {'x': np.array([573.25446, 1000.21721, 983.92918, 546.00285, 518.2782])-1,\n 'y': np.array([512., 10, 100, 900, 1014])-1,\n 's': np.array([8, 1, 1, 16, 16]),\n 'alpha': np.array([0., -2.94573, 3.09057, -3.07810, 2.73161]),\n 'beta': np.array([-0.19491, -2.92360, -2.92360, 2.92360, 2.92360]),\n 'lam': np.array([16.79017, 18.08441, 17.86845, 15.76948, 15.43724]),\n 'xan': np.array([-8.40205, -8.44574, -8.34664, -8.45859, -8.36196]),\n 'yan': np.array([-2.48627, -2.53761, -2.52502, -2.44221, -2.42787]),\n },\n '4A': {'x': np.array([80.987181, 434.34987, 461.90855, 26.322503, 53.674656])-1,\n 'y': np.array([512., 10, 100, 900, 1014])-1,\n 's': np.array([6, 1, 1, 12, 12]),\n 'alpha': np.array([0., -3.74625, 3.72621, -3.94261, 3.62762]),\n 'beta': np.array([-0.32802, -3.60821, -3.60821, 3.60821, 3.60821]),\n 'lam': np.array([19.34914, 20.93078, 20.6464, 18.07975, 17.67221]),\n 'xan': np.array([-8.38446, -8.43506, -8.31378, -8.46256, -8.33609]),\n 'yan': np.array([-2.48058, -2.5444, -2.52426, -2.42449, -2.40839])\n },\n '4B': {'x': np.array([77.625553, 431.57061, 458.86869, 23.559111, 50.632416])-1,\n 'y': np.array([512., 10, 100, 900, 1014])-1,\n 's': np.array([6, 1, 1, 12, 12]),\n 'alpha': np.array([0., -3.64817, 3.73313, -3.73558, 3.74096]),\n 'beta': np.array([-0.32802, -3.60821, -3.60821, 3.60821, 3.60821]),\n 'lam': np.array([22.38267, 24.21212, 23.88327, 20.91426, 20.44279]),\n 'xan': np.array([-8.38581, -8.43443, -8.3141, -8.46152, -8.33604]),\n 'yan': np.array([-2.48185, -2.54526, -2.52568, -2.42513, -2.40959])\n },\n '4C': {'x': np.array([79.662059, 433.73384, 460.75026, 25.820431, 52.412219])-1,\n 'y': np.array([512., 10, 100, 900, 1014])-1,\n 's': np.array([6, 1, 1, 12, 12]),\n 'alpha': np.array([0., -3.61682, 3.69713, -3.66259, 3.69888]),\n 'beta': np.array([-0.32802, -3.60819, -3.60819, 3.60819, 3.60819]),\n 'lam': np.array([26.18343, 28.32354, 27.93894, 24.46574, 23.91417]),\n 'xan': np.array([-8.38603, -8.43509, -8.31524, -8.45888, -8.33707]),\n 'yan': np.array([-2.48315, -2.54647, -2.52661, -2.42721, -2.41060])\n }\n}\n" ]
[ [ "numpy.array" ] ]
ismedina/geomloss
[ "bbd6289a139174effedb6855e1e992eb77772c67" ]
[ "geomloss/examples/optimal_transport/plot_wasserstein_barycenters_1D.py" ]
[ "\"\"\"\nWasserstein barycenters in 1D\n==================================\n\nLet's compute Wasserstein barycenters\nwith a Sinkhorn divergence,\nusing Eulerian and Lagrangian optimization schemes.\n\"\"\"\n\n##############################################\n# Setup\n# ---------------------\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.neighbors import KernelDensity # display as density curves\n\nimport torch\nfrom geomloss import SamplesLoss\n\nuse_cuda = torch.cuda.is_available()\ndtype = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor\n\n###############################################\n# Dataset\n# ~~~~~~~~~~~~~~~~~~\n#\n# Given a weight :math:`w\\in[0,1]`\n# and two *endpoint* measures :math:`\\alpha`\n# and :math:`\\beta`, we wish to compute\n# the **Sinkhorn barycenter**\n#\n# .. math::\n# \\gamma^\\star ~=~ \\arg\\min_{\\gamma}~\n# (1-w)\\cdot\\text{S}_{\\varepsilon,\\rho}(\\gamma,\\alpha)\n# \\,+\\, w\\cdot\\text{S}_{\\varepsilon,\\rho}(\\gamma,\\beta),\n#\n# which coincides with :math:`\\alpha` when :math:`w=0`\n# and with :math:`\\beta` when :math:`w=1`.\n#\n# If our input measures\n#\n# .. math::\n# \\alpha ~=~ \\frac{1}{M}\\sum_{i=1}^M \\delta_{x_i}, ~~~\n# \\beta ~=~ \\frac{1}{M}\\sum_{j=1}^M \\delta_{y_j},\n#\n# are fixed, the optimization problem\n# above is `known to be convex <https://arxiv.org/abs/1810.08278>`_ with\n# respect to the weights :math:`\\gamma_k` of the *variable* measure\n#\n# .. math::\n# \\gamma ~=~ \\sum_{k=1}^N \\gamma_k\\,\\delta_{z_k}.\n\n\nN, M = (50, 50) if not use_cuda else (500, 500)\n\nt_i = torch.linspace(0, 1, M).type(dtype).view(-1, 1)\nt_j = torch.linspace(0, 1, M).type(dtype).view(-1, 1)\n\nX_i, Y_j = 0.1 * t_i, 0.2 * t_j + 0.8 # Intervals [0., 0.1] and [.8, 1.].\n\n\n###############################################\n# In this notebook, we thus propose to solve the barycentric\n# optimization problem through a (quasi-)convex optimization\n# on the (log-)weights :math:`\\log(\\gamma_k)` - with fixed :math:`\\delta_{z_k}`'s -\n# and through a well-conditioned\n# descent on the samples' positions :math:`\\delta_{z_k}`\n# - with uniform weights :math:`\\gamma_k = 1/N`.\n#\n# In both sections (Eulerian vs. Lagrangian), we'll start from a\n# uniform sample on the unit interval:\n\nt_k = torch.linspace(0, 1, N).type(dtype).view(-1, 1)\nZ_k = t_k\n\n\n###############################################\n# Display routine\n# ~~~~~~~~~~~~~~~~~\n#\n# We display our samples using (smoothed) density\n# curves, computed with a straightforward Gaussian convolution:\n\nt_plot = np.linspace(-0.1, 1.1, 1000)[:, np.newaxis]\n\n\ndef display_samples(ax, x, color, weights=None, blur=0.002):\n \"\"\"Displays samples on the unit interval using a density curve.\"\"\"\n kde = KernelDensity(kernel=\"gaussian\", bandwidth=blur).fit(\n x.data.cpu().numpy(),\n sample_weight=None if weights is None else weights.data.cpu().numpy(),\n )\n dens = np.exp(kde.score_samples(t_plot))\n dens[0] = 0\n dens[-1] = 0\n ax.fill(t_plot, dens, color=color)\n\n\n###############################################\n# Eulerian gradient flow\n# ------------------------------------------\n#\n# Taking advantage of the **convexity** of Sinkhorn divergences\n# with respect to the measures' weights, we first solve\n# the barycentric optimization problem through a\n# (quasi-convex) **Eulerian**\n# descent on the **log-weights** :math:`l_k = \\log(\\gamma_k)`:\n\n\nfrom geomloss.examples.optimal_transport.model_fitting import (\n fit_model,\n) # Wrapper around scipy.optimize\nfrom torch.nn import Module, Parameter # PyTorch syntax for optimization problems\n\n\nclass Barycenter(Module):\n \"\"\"Abstract model for the computation of Sinkhorn barycenters.\"\"\"\n\n def __init__(self, loss, w=0.5):\n super(Barycenter, self).__init__()\n self.loss = loss # Sinkhorn divergence to optimize\n self.w = w # Interpolation coefficient\n # We copy the reference starting points, to prevent in-place modification:\n self.x_i, self.y_j, self.z_k = X_i.clone(), Y_j.clone(), Z_k.clone()\n\n def fit(self, display=False, tol=1e-10):\n \"\"\"Uses a custom wrapper around the scipy.optimize module.\"\"\"\n fit_model(self, method=\"L-BFGS\", lr=1.0, display=display, tol=tol, gtol=tol)\n\n def weights(self):\n \"\"\"The default weights are uniform, equal to 1/N.\"\"\"\n return (torch.ones(len(self.z_k)) / len(self.z_k)).type_as(self.z_k)\n\n def plot(self, nit=0, cost=0, ax=None, title=None):\n \"\"\"Displays the descent using a custom 'waffle' layout.\n\n N.B.: As the L-BFGS descent typically induces high-frequencies in\n the optimization process, we blur the 'interpolating' measure\n a little bit more than the two endpoints.\n \"\"\"\n if ax is None:\n if nit == 0 or nit % 16 == 4:\n plt.pause(0.01)\n plt.figure(figsize=(16, 4))\n\n if nit <= 4 or nit % 4 == 0:\n if nit < 4:\n index = nit + 1\n else:\n index = (nit // 4 - 1) % 4 + 1\n ax = plt.subplot(1, 4, index)\n\n if ax is not None:\n display_samples(ax, self.x_i, (0.95, 0.55, 0.55))\n display_samples(ax, self.y_j, (0.55, 0.55, 0.95))\n display_samples(\n ax, self.z_k, (0.55, 0.95, 0.55), weights=self.weights(), blur=0.005\n )\n\n if title is None:\n ax.set_title(\"nit = {}, cost = {:3.4f}\".format(nit, cost))\n else:\n ax.set_title(title)\n\n ax.axis([-0.1, 1.1, -0.1, 20.5])\n ax.set_xticks([], [])\n ax.set_yticks([], [])\n plt.tight_layout()\n\n\nclass EulerianBarycenter(Barycenter):\n \"\"\"Barycentric model with fixed locations z_k, as we optimize on the log-weights l_k.\"\"\"\n\n def __init__(self, loss, w=0.5):\n super(EulerianBarycenter, self).__init__(loss, w)\n\n # We're going to work with variable weights, so we should explicitely\n # define the (uniform) weights on the \"endpoint\" samples:\n self.a_i = (torch.ones(len(self.x_i)) / len(self.x_i)).type_as(self.x_i)\n self.b_j = (torch.ones(len(self.y_j)) / len(self.y_j)).type_as(self.y_j)\n\n # Our parameter to optimize: the logarithms of our weights\n self.l_k = Parameter(torch.zeros(len(self.z_k)).type_as(self.z_k))\n\n def weights(self):\n \"\"\"Turns the l_k's into the weights of a positive probabilty measure.\"\"\"\n return torch.nn.functional.softmax(self.l_k, dim=0)\n\n def forward(self):\n \"\"\"Returns the cost to minimize.\"\"\"\n c_k = self.weights()\n return self.w * self.loss(c_k, self.z_k, self.a_i, self.x_i) + (\n 1 - self.w\n ) * self.loss(c_k, self.z_k, self.b_j, self.y_j)\n\n\n###############################################\n# For this first experiment, we err on the side of caution\n# and use a small **blur** value in conjuction\n# with a large **scaling** coefficient - i.e. a large number of iterations\n# in the Sinkhorn loop:\n\nEulerianBarycenter(SamplesLoss(\"sinkhorn\", blur=0.001, scaling=0.99)).fit(display=True)\n\n#############################################\n# As evidenced here, the **Eulerian** descent fits **one by one**\n# the Fourier modes of the \"true\" Wasserstein barycenter:\n# we start from a Gaussian blob and progressively\n# integrate the higher frequencies, slowly converging\n# towards a **sharp** step function.\n\n\n###############################################\n# Lagrangian gradient flow\n# ------------------------------------------\n#\n# The procedure above is theoretically sound (thanks to the **convexity** of\n# Sinkhorn divergences),\n# but may be too slow for practical purposes.\n# A simple workaround is to tackle the barycentric interpolation problem\n# using a Lagrangian, particular scheme and optimize our weighted\n# loss with respect to the **samples' positions**:\n\n\nclass LagrangianBarycenter(Barycenter):\n def __init__(self, loss, w=0.5):\n super(LagrangianBarycenter, self).__init__(loss, w)\n\n # Our parameter to optimize: the locations of the input samples\n self.z_k = Parameter(Z_k.clone())\n\n def forward(self):\n \"\"\"Returns the cost to minimize.\"\"\"\n # By default, the weights are uniform and sum up to 1:\n return self.w * self.loss(self.z_k, self.x_i) + (1 - self.w) * self.loss(\n self.z_k, self.y_j\n )\n\n\n###############################################\n# As evidenced below, this algorithm converges quickly towards\n# a decent interpolator, even for small-ish values of the scaling coefficient:\n\nLagrangianBarycenter(SamplesLoss(\"sinkhorn\", blur=0.01, scaling=0.9)).fit(display=True)\n\n\n###############################################\n# This algorithm can be understood as a generalization\n# of :doc:`Optimal Transport registration <plot_optimal_transport_2D>`\n# to **multi-target** applications and can be used\n# to compute efficiently some :doc:`Wasserstein barycenters in 2D <plot_wasserstein_barycenters_2D>`.\n# The trade-off between speed and accuracy (especially with respect to oscillating artifacts)\n# can be tuned with the **tol** and **scaling** parameters:\n\nLagrangianBarycenter(SamplesLoss(\"sinkhorn\", blur=0.01, scaling=0.5)).fit(\n display=True, tol=1e-5\n)\nplt.show()\n" ]
[ [ "torch.linspace", "matplotlib.pyplot.figure", "torch.cuda.is_available", "matplotlib.pyplot.tight_layout", "sklearn.neighbors.KernelDensity", "torch.nn.functional.softmax", "matplotlib.pyplot.pause", "matplotlib.pyplot.show", "numpy.linspace", "matplotlib.pyplot.subplot" ] ]
pstroe/goldberg_nnm4nlp
[ "2b66842e4c85b882c3c22959b3522daff3465493" ]
[ "lib/language_classification.py" ]
[ "\n# coding: utf-8\n\n# # Multi-Class Classification - Language Classification\n# \n# This notebook implements the method presented in Goldberg's [2017] book \"Neural Network Methods for Natural Language Processing\". It shows the steps you need to go through in order to successfully train a classifier, and it should also, so I hope, illustrate the notational differences between Goldberg and standard machine learning literature.\n# \n# $NOTE$: There is no cross-validation etc. to find optimal parameters. This is simply to show how multi-class classification works. This will be part of a tutorial session and all other concepts will be explained there.\n# \n# Author: Phillip Ströbel\n\n# ## Getting and cleaning the data\n# \n# The data consists of downloaded Wikipedia articles (see `urls.txt`) in German, English, French, Spanish, Italian and Finnish (instead of \"O\" in Goldberg). The data is in HTML, so we need to some preprocessing to get the text out of it. We also restrict ourselfes to the characters from a to z in the alphabet (as described in Goldberg). In this fashion, we get rid of all the Umlauts (ä, ö, ü) and all other characters with diacritics (as, e.g., the é or ç in French). Note however, that if these characters ocurring in bigrams would probably be good features. In some way, we still keep the information \"special character\" by not fully deleting the character, but by replacing it by the dollar sign \"\\$\". Furthermore, we replace all punctuation marks and digits by dollar signs as well. As such, all special characters, digits, and punctuation marks are mapped to $. The space will be replaced by an underscore \"\\_\". We then represent each langauge by 28 characters, as is suggested by Goldberg.\n\n# ### Cleaning HTML\n# We first strip the HTML to get only the text of the Wikipedia page.\n\n# #### Get the html files\n\n# In[2]:\n\n\nimport re\nimport numpy as np\nfrom bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nfrom collections import defaultdict\n\nseed = np.random.seed(seed=200) # set a seed for random, so results are reproducible\n\narticle_dict = defaultdict(lambda: defaultdict(str))\n\nregex = r'[\\n ]{2,}'\npattern = re.compile(regex)\n\nurls = open('urls.txt', 'r').readlines()\n\nfor index, url in enumerate(urls):\n language = url[8:10]\n doc_id = 'doc_%d' % index\n html = urlopen(url.strip()).read() \n soup = BeautifulSoup(html, 'html.parser')\n raw = soup.body.get_text() # only get text from the text body (this excludes headers and should exclude navigation bars)\n raw = re.sub(pattern, ' ', raw) # replace multiple breaks and spaces by only one space\n raw = re.sub(r'\\n', ' ', raw) # replace every line break with a space\n article_dict[language][doc_id] = raw.lower() # assign each text to its language and lower all uppercase characters\n\n\n# ### Preprocessing --> prepare the text\n# replace special characters and digits\n\n# In[3]:\n\n\npreprocessed_dict = defaultdict(lambda: defaultdict(str))\n\nabc = r'[a-z]'\nabc_pattern = re.compile(abc)\n\nfor lang, doc in article_dict.items():\n for doc, text in doc.items():\n for char in text:\n if re.match(abc_pattern, char):\n preprocessed_dict[lang][doc] += char\n elif re.match(' ', char):\n preprocessed_dict[lang][doc] += '_'\n else:\n preprocessed_dict[lang][doc] += '$'\n\n\n# ### Count bigrams --> Feature extraction\n\n# The distribution of bigrams will be our only feature. We could extend this by taking into account other n-grams.\n\n# In[4]:\n\n\ncharset = 'abcdefghijklmnopqrstuvwxyz$_' # define the character set we want to use\n\n\n# In[5]:\n\n\nfrom itertools import combinations_with_replacement, permutations\n\ndef bigrams(text):\n \"\"\"\n Function to extract bigrams from text and calculate their distribution\n :param text: text string\n :return: dictionary containing bigrams as keys, and the normalised count as values\n \"\"\"\n combs = combinations_with_replacement(charset, 2)\n perms = permutations(charset, 2)\n bigram_dict = dict()\n \n for comb in set(list(combs) + list(perms)):\n bigram_dict[''.join(comb)] = 0\n \n doc_length = len(text)\n \n for index in range(0, len(text)-1):\n bigram = text[index] + text[index+1]\n bigram_dict[bigram] += 1\n \n for bigram, count in bigram_dict.items():\n bigram_dict[bigram] = count/doc_length\n\n return bigram_dict \n\n\n# ### Put data into pandas dataframe\n# The pandas dataframe allows us to conveniently represent all the data we need in one table. So let's do this. But first we need to extract the features.\n\n# In[6]:\n\n\nbigram_dict_full = defaultdict(lambda: defaultdict(dict))\n\nfor lang, doc in preprocessed_dict.items():\n for doc, text in sorted(doc.items()):\n bigram_dict = bigrams(text)\n bigram_dict_full[lang][doc] = bigram_dict\n\n\n# In[7]:\n\n\nimport pandas as pd\n\ncol_names = ['y'] + sorted(bigram_dict_full['en']['doc_0'].keys())\nmy_df = dict()\n\nfor col in col_names:\n my_df[col] = list()\n \ndf = pd.DataFrame(my_df)\n\nfor lang, doc in bigram_dict_full.items():\n for key, value in doc.items():\n df_obj = value\n df_obj['y'] = lang\n df = df.append(df_obj, ignore_index=True)\n \ndf.head()\n \n\n\n# In[8]:\n\n\ndf.shape\n\n\n# Now we split the data into the label vector \\begin{equation}\\mathbf{y}\\end{equation} and a training data matrix \\begin{equation}\\mathbf{X}\\end{equation}. But first, we shuffle the df and split it into a training and a test set.\n\n# Moreover, it is necessary for many machine learning tasks to standardise the data. Our aim is for each feature to be represented by a column vector in which values have zero mean and unit variance.\n\n# In[9]:\n\n\ndef normalise_point(datapoint, mean, std):\n \"\"\"\n normalise a datapoint to zero mean and unit variance.\n :param datapoint: value as a float\n :param mean: mean of data vector x\n :param std: standard deviation of data vector x\n :return: normalised datapoint (float)\n \"\"\"\n return (datapoint - mean)/std\n\ndef normalise_matrix(matrix):\n \"\"\"\n normalises the data matrix\n :param matrix: input matrix\n :return: normalised matrix\n \"\"\"\n train_normalised = matrix.copy()\n \n for col in matrix:\n try:\n mean = matrix[col].mean()\n std = matrix[col].std()\n for index, item in enumerate(matrix[col]):\n train_normalised.loc[index, col] = normalise_point(item, mean, std)\n except ZeroDivisionError:\n train_normalised.loc[index, col] = 0.0\n except TypeError:\n continue\n return train_normalised\n\n\n# In[10]:\n\n\ndf_norm = normalise_matrix(df)\n\n\n# Split the data into a train set and a test set\n\n# In[11]:\n\n\ntrain = df_norm.sample(frac=0.9, random_state=seed)\ntest = df_norm.drop(train.index)\n\n\n# Define the different sets\n\n# In[12]:\n\n\n# for training\ny_train = train.y\nX_train = train.drop('y', axis=1)\n\n# for testing\ny_test = test.y\nX_test = test.drop('y', axis=1)\n\n\n# Check the shapes\n\n# In[13]:\n\n\nprint('Training samples shape: ', X_train.shape)\nprint('Training labels shape: ', y_train.shape)\nprint('Test samples shape: ', X_test.shape)\nprint('Test labels shape: ', y_test.shape)\n\n\n# We should binarise our labels, although libraries like sklearn can also deal with non-numeric data\n\n# In[14]:\n\n\nfrom sklearn import preprocessing\n\nlb = preprocessing.LabelBinarizer()\nlb.fit(['en', 'fr', 'de', 'it', 'es', 'fi'])\n\n\n# In[15]:\n\n\nlb.classes_\n\n\n# We do this for both our training and test labels:\n\n# In[16]:\n\n\ny_train = lb.transform(y_train)\ny_test = lb.transform(y_test)\n\n\n# Labels are now one-hot encoded:\n\n# In[17]:\n\n\ny_train[0]\n\n\n# We almost have everything now. However, we need to take care of the bias and the weight matrix. The hypothesis ŷ is given by:\n# \\begin{equation}\n# \\mathbf{\\hat{y}}=\\mathbf{x}\\cdot\\mathbf{W}+\\mathbf{b}\n# \\end{equation}\n# We can achieve this by appending 1 to each feature vector x, and the whole weight vector b to the weight matrix W. This is called the bias trick. Note that the dimensions of X_train change, and that the weight matrix W will have match the dimensions (same number of rows as X has columns).\n\n# In[18]:\n\n\nbias_vector = np.ones([X_train.shape[0], 1])\nX_train['bias'] = bias_vector\nX_train\n\n\n# In[19]:\n\n\n# initialise weight matrix with small weights\n\nnp.random.seed(seed=200)\n\nW = np.random.randn(X_train.shape[1], len(lb.classes_)) * 0.0001\n#W = np.zeros([X.shape[1], len(lb.classes_)])\n\n\n# We see that the dimensions are right. The dot product of a specific row from X_train and the weight matrix W constitutes a forward pass and calculates the score for each class.\n\n# In[20]:\n\n\nW.shape\n\n\n# In[21]:\n\n\nX_train.shape\n\n\n# In[22]:\n\n\nX_train[5:6].dot(W)\n\n\n# We see that the values for the highest score of the dot product is not the score of the true label. Our aim is to change this by implementing a support vector classifier.\n\n# In[23]:\n\n\nX_train[5:6].dot(W).max(axis=1)\n\n\n# In[24]:\n\n\nX_train[5:6].dot(W)[y_train[5:6].argmax()]\n\n\n# Important: we follow kind of a naive implementation. The aim is to be able to understand what is going on!\n# \n# In order to quantify how good (or how bad) our weight matrix W can predict the data in our training set, we need to implement a loss function. Here we take a go at the hinge loss, which tries to predict the correct class with a margin of at least one to all other classes (or in this case, like presented in Goldberg, to the class which does not equal the true class, but which scores highest). In my understanding, this is a one-vs-one approach (true class vs. class with highest score (but doesn't equal the true class)).\n\n# In[116]:\n\n\ndef hinge_loss(x, y, W, index):\n \"\"\"\n Calculates the loss of a single data point by taking the prediction of the correct value and the the prediction of\n the value of next highest score, following Crammer and Singer (2001)\n :param x: sample point x as a vector\n :param y: correct label y for x as a vector\n :param W: weight matrix\n :param index: column index of data matrix X\n :return: loss\n \"\"\"\n loss = 0\n y_index = y[index].argmax()\n y_value = x.dot(W)[y_index]\n y_hat_max_value = np.delete(x.dot(W), y_index).max()\n #for j in range(0, y.shape[1]): # in case we wanted to classify against all other classes (one-vs-all) --> currently one-vs-one\n #if j == y_index:\n #continue\n loss += max(0, 1 - (y_value - y_hat_max_value))\n return loss\n\n\n# With matrix multiplication, we could get all the scores at once. In the following, however, we focus on an approach which takes sample by sample and calculates the loss and the gradients.\n\n# In[26]:\n\n\nscores = X_train.dot(W) # simple matrix multiplication to get all scores\n\n\n# In[27]:\n\n\nscores\n\n\n# In[120]:\n\n\ndef gradient(X, y, W):\n \"\"\"\n compute the gradient\n :param X: data matrix (train) \n :param y: the corresponding \n :param W: weight matrix\n :return: loss and Jacobian dW with all gradients\n \"\"\"\n dW = np.zeros(W.shape)\n \n total_loss = 0.0\n \n for index, x in enumerate(X.as_matrix()):\n y_index = y[index].argmax()\n y_value = x.dot(W)[y_index]\n y_hat_max_value = np.delete(x.dot(W), y_index).max()\n loss = max(0, 1 - (y_value - y_hat_max_value))\n total_loss += loss\n y_hat_max_index = np.delete(x.dot(W), y_index).argmax() + 1\n if loss > 0: # not sure whether we need this if statement\n dW[:, y_hat_max_index] += x.transpose()\n dW[:, y_index] -= x.transpose()\n \n return total_loss, dW\n \n\n\n# In[121]:\n\n\ndef gradient_descent(X, y, W, eta, steps):\n \"\"\"\n Perform gradient descent for a number of times with a fixed learning rate eta\n :param X: data matrix\n :param y: labels\n :param W: weight matrix\n :param eta: learning rate\n :param steps: number of times gradient descent should be performed\n :return: learned representation matrix W_learned\n \"\"\"\n W_learned = W.copy()\n \n for step in range(0, steps):\n loss, dW = gradient(X, y, W_learned)\n print(loss)\n W_learned = W_learned - eta * dW\n \n return W_learned\n \n\n\n# In[122]:\n\n\nW_star = gradient_descent(X_train, y_train, W, eta=0.001, steps=10)\n\n\n# ### Testing\n# Let's test if our learned representation of the data is any good at classifying the data in the test set. Of course we need the bias in our test set as well!\n\n# In[83]:\n\n\nbias_vector_test = np.ones([X_test.shape[0], 1])\nX_test['bias'] = bias_vector_test\n\n\n# In[84]:\n\n\nfor index, x in enumerate(X_test.dot(W_star).as_matrix()):\n pred = x.argmax()\n true_label = y_test[index].argmax()\n print(pred, true_label)\n\n\n# Not too bad! But Goldberg mentioned something about regularisation, so we should take this into account as well!\n\n# In[113]:\n\n\ndef gradient_reg(X, y, W, lam):\n \"\"\"\n compute the gradient\n :param X: data matrix (train) \n :param y: the corresponding \n :param W: weight matrix\n :param lam: reguliser lambda\n :return: Jacobian dW with all gradients\n \"\"\"\n dW = np.zeros(W.shape)\n \n total_loss = 0.0\n \n for index, x in enumerate(X.as_matrix()):\n y_index = y[index].argmax()\n y_value = x.dot(W)[y_index]\n y_hat_max_value = np.delete(x.dot(W), y_index).max()\n loss = max(0, 1 - (y_value - y_hat_max_value)) + lam * np.linalg.norm(W, 2)\n total_loss += loss\n y_hat_max_index = np.delete(x.dot(W), y_index).argmax() + 1\n if loss > 0: # not sure whether we need this if statement\n dW[:, y_hat_max_index] += x.transpose()\n dW[:, y_index] -= x.transpose()\n \n dW += 2 * lam * W\n \n return total_loss, dW\n\ndef gradient_descent_reg(X, y, W, eta, steps):\n \"\"\"\n Perform gradient descent for a number of times with a fixed learning rate eta\n :param X: data matrix\n :param y: labels\n :param W: weight matrix\n :param eta: learning rate\n :param steps: number of times gradient descent should be performed\n :return: learned representation matrix W_learned\n \"\"\"\n W_learned = W.copy()\n \n for step in range(0, steps):\n loss, dW = gradient_reg(X, y, W_learned, 10)\n print(loss)\n W_learned = W_learned - eta * dW\n \n return W_learned\n \n\n\n# In[114]:\n\n\nW_star_reg = gradient_descent_reg(X_train, y_train, W, eta=0.001, steps=10)\n\n\n# In[115]:\n\n\nfor index, x in enumerate(X_test.dot(W_star_reg).as_matrix()):\n pred = x.argmax()\n true_label = y_test[index].argmax()\n print(pred, true_label)\n\n\n# If we look at the two different weight matrices (one regularised, the other not), we notice the following:\n\n# In[109]:\n\n\nW_star[0:5]\n\n\n# In[110]:\n\n\nW_star_reg[0:5]\n\n\n# ## By the way ...\n# ### In scikit-learn it's much easier to implement this :-)\n# \n\n# In[39]:\n\n\nfrom sklearn.svm import LinearSVC\nclf = LinearSVC(random_state=0, multi_class='crammer_singer', loss='hinge')\nclf.fit(X_train, train.y)\n\n\n# In[40]:\n\n\nclf.predict(X_test)\n\n\n# In[41]:\n\n\ntest.y\n\n\n# We see that with our naive implementation, we do not much worse than with scikit's. scikit's implementation is of course much more elaborate and uses the vectorised operation and possibly other optimisation techniques in order to make its SVM (or SVC) better.\n" ]
[ [ "numpy.linalg.norm", "numpy.zeros", "numpy.random.seed", "pandas.DataFrame", "numpy.ones", "sklearn.preprocessing.LabelBinarizer", "sklearn.svm.LinearSVC" ] ]
rzumer/VideoLowLevelVision
[ "1c15dbe74f0b33d2e74d0a717a22ccbd67cdf269" ]
[ "VLLV/Models/Dbpn.py" ]
[ "\"\"\"\nCopyright: Wenyi Tang 2017-2018\nAuthor: Wenyi Tang\nEmail: [email protected]\nCreated Date: June 15th 2018\nUpdated Date: Sep 11th 2018\n\nDeep Back-Projection Networks For Super-Resolution (CVPR 2018)\nSee https://arxiv.org/abs/1803.02735\n\"\"\"\n\nfrom VLLV.Framework.SuperResolution import SuperResolution\n\nimport tensorflow as tf\nimport numpy as np\n\n\nclass DBPN(SuperResolution):\n \"\"\"Deep Back-Projection Networks For Super-Resolution\n\n Args:\n bp_layers: number of back-projection stages\n use_dense: use dense unit or not\n filters: number of filters in primary conv2d(s)\n \"\"\"\n\n def __init__(self, bp_layers=7, use_dense=True, filters=64, name='dbpn', **kwargs):\n super(DBPN, self).__init__(**kwargs)\n self.bp = bp_layers\n self.dense = use_dense\n self.filter = filters\n self.name = name\n s0, s1 = self.scale\n assert s0 == s1\n if s0 == 3:\n self.kernel_size = 7\n elif s0 == 2 or s0 == 4 or s0 == 8:\n self.kernel_size = int(4 + 2 * np.log2(s0))\n\n def _up_projection(self, inputs, dense=True, **kwargs):\n with tf.variable_scope(kwargs.get('name'), 'UpProjection'):\n if dense:\n L_pre = self.conv2d(inputs, self.filter, 1, activation='prelu')\n else:\n L_pre = inputs\n H0 = self.deconv2d(L_pre, self.filter, self.kernel_size, self.scale, activation='prelu')\n L0 = self.conv2d(H0, self.filter, self.kernel_size, self.scale, activation='prelu')\n res_cur = L0 - L_pre\n H1 = self.deconv2d(res_cur, self.filter, self.kernel_size, self.scale, activation='prelu')\n H_cur = H0 + H1\n return H_cur\n\n def _down_projection(self, inputs, dense=True, **kwargs):\n with tf.variable_scope(kwargs.get('name'), 'DownProjection'):\n if dense:\n H_pre = self.conv2d(inputs, self.filter, 1, activation='prelu')\n else:\n H_pre = inputs\n L0 = self.conv2d(H_pre, self.filter, self.kernel_size, self.scale, activation='prelu')\n H0 = self.deconv2d(L0, self.filter, self.kernel_size, strides=self.scale, activation='prelu')\n res_cur = H0 - H_pre\n L1 = self.conv2d(res_cur, self.filter, self.kernel_size, self.scale, activation='prelu')\n L_cur = L0 + L1\n return L_cur\n\n def build_graph(self):\n super(DBPN, self).build_graph()\n with tf.variable_scope(self.name):\n with tf.variable_scope('FE-Net'):\n x = self.conv2d(self.inputs_preproc[-1], 256, 3, activation='prelu')\n x = self.conv2d(x, self.filter, 1, activation='prelu')\n with tf.variable_scope('BP-Net'):\n L, H = [x], []\n for _ in range(1, self.bp):\n t = tf.concat(L, axis=-1) if self.dense else L[-1]\n H.append(self._up_projection(t, self.dense))\n t = tf.concat(H, axis=-1) if self.dense else H[-1]\n L.append(self._down_projection(t, self.dense))\n t = tf.concat(L, axis=-1) if self.dense else L[-1]\n H.append(self._up_projection(t, self.dense))\n x = tf.concat(H, axis=-1)\n with tf.variable_scope('ReconNet'):\n x = self.conv2d(x, self.channel, 3)\n self.outputs.append(x)\n\n def build_loss(self):\n with tf.name_scope('Loss'):\n l1_loss = tf.losses.absolute_difference(self.label[0], self.outputs[0])\n re_loss = tf.losses.get_regularization_losses()\n mse = tf.losses.mean_squared_error(self.label[0], self.outputs[0])\n loss = tf.add_n(re_loss + [l1_loss], name='Loss')\n\n update_op = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_op):\n opt = tf.train.AdamOptimizer(self.learning_rate).minimize(loss, self.global_steps)\n self.loss.append(opt)\n\n # tensorboard\n self.train_metric['loss'] = loss\n self.train_metric['l1'] = l1_loss\n self.metrics['mse'] = mse\n self.metrics['psnr'] = tf.reduce_mean(tf.image.psnr(self.label[0], self.outputs[0], 255))\n self.metrics['ssim'] = tf.reduce_mean(tf.image.ssim(self.label[0], self.outputs[0], 255))\n\n def build_summary(self):\n tf.summary.scalar('loss', self.train_metric['loss'])\n tf.summary.scalar('mse', self.metrics['mse'])\n tf.summary.scalar('psnr', self.metrics['psnr'])\n tf.summary.scalar('ssim', self.metrics['ssim'])\n tf.summary.image('SR', self.outputs[0], 1)\n" ]
[ [ "tensorflow.control_dependencies", "tensorflow.summary.image", "tensorflow.losses.get_regularization_losses", "tensorflow.concat", "tensorflow.train.AdamOptimizer", "tensorflow.summary.scalar", "tensorflow.image.psnr", "tensorflow.losses.absolute_difference", "tensorflow.add_n", "tensorflow.variable_scope", "tensorflow.name_scope", "tensorflow.losses.mean_squared_error", "tensorflow.image.ssim", "numpy.log2", "tensorflow.get_collection" ] ]
jeromekelleher/zarr
[ "3c8e9291e96e090e20caf6950da69a3cc180652f" ]
[ "zarr/core.py" ]
[ "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, print_function, division\nimport binascii\nimport operator\nimport itertools\nimport hashlib\nimport re\n\n\nimport numpy as np\n\n\nfrom zarr.util import (is_total_slice, human_readable_size, normalize_resize_args,\n normalize_storage_path, normalize_shape, normalize_chunks,\n InfoReporter, check_array_shape, nolock)\nfrom zarr.storage import array_meta_key, attrs_key, listdir, getsize\nfrom zarr.meta import decode_array_metadata, encode_array_metadata\nfrom zarr.attrs import Attributes\nfrom zarr.errors import PermissionError, err_read_only, err_array_not_found\nfrom zarr.compat import reduce\nfrom zarr.codecs import AsType, get_codec\nfrom zarr.indexing import (OIndex, OrthogonalIndexer, BasicIndexer, VIndex,\n CoordinateIndexer, MaskIndexer, check_fields, pop_fields,\n ensure_tuple, is_scalar, is_contiguous_selection,\n err_too_many_indices, check_no_multi_fields)\n\n\n# noinspection PyUnresolvedReferences\nclass Array(object):\n \"\"\"Instantiate an array from an initialized store.\n\n Parameters\n ----------\n store : MutableMapping\n Array store, already initialized.\n path : string, optional\n Storage path.\n read_only : bool, optional\n True if array should be protected against modification.\n chunk_store : MutableMapping, optional\n Separate storage for chunks. If not provided, `store` will be used\n for storage of both chunks and metadata.\n synchronizer : object, optional\n Array synchronizer.\n cache_metadata : bool, optional\n If True (default), array configuration metadata will be cached for the\n lifetime of the object. If False, array metadata will be reloaded\n prior to all data access and modification operations (may incur\n overhead depending on storage and data access pattern).\n cache_attrs : bool, optional\n If True (default), user attributes will be cached for attribute read\n operations. If False, user attributes are reloaded from the store prior\n to all attribute read operations.\n\n Attributes\n ----------\n store\n path\n name\n read_only\n chunk_store\n shape\n chunks\n dtype\n compression\n compression_opts\n fill_value\n order\n synchronizer\n filters\n attrs\n size\n itemsize\n nbytes\n nbytes_stored\n cdata_shape\n nchunks\n nchunks_initialized\n is_view\n info\n vindex\n oindex\n\n Methods\n -------\n __getitem__\n __setitem__\n get_basic_selection\n set_basic_selection\n get_orthogonal_selection\n set_orthogonal_selection\n get_mask_selection\n set_mask_selection\n get_coordinate_selection\n set_coordinate_selection\n digest\n hexdigest\n resize\n append\n view\n astype\n\n \"\"\"\n\n def __init__(self, store, path=None, read_only=False, chunk_store=None,\n synchronizer=None, cache_metadata=True, cache_attrs=True):\n # N.B., expect at this point store is fully initialized with all\n # configuration metadata fully specified and normalized\n\n self._store = store\n self._chunk_store = chunk_store\n self._path = normalize_storage_path(path)\n if self._path:\n self._key_prefix = self._path + '/'\n else:\n self._key_prefix = ''\n self._read_only = bool(read_only)\n self._synchronizer = synchronizer\n self._cache_metadata = cache_metadata\n self._is_view = False\n\n # initialize metadata\n self._load_metadata()\n\n # initialize attributes\n akey = self._key_prefix + attrs_key\n self._attrs = Attributes(store, key=akey, read_only=read_only,\n synchronizer=synchronizer, cache=cache_attrs)\n\n # initialize info reporter\n self._info_reporter = InfoReporter(self)\n\n # initialize indexing helpers\n self._oindex = OIndex(self)\n self._vindex = VIndex(self)\n\n def _load_metadata(self):\n \"\"\"(Re)load metadata from store.\"\"\"\n if self._synchronizer is None:\n self._load_metadata_nosync()\n else:\n mkey = self._key_prefix + array_meta_key\n with self._synchronizer[mkey]:\n self._load_metadata_nosync()\n\n def _load_metadata_nosync(self):\n try:\n mkey = self._key_prefix + array_meta_key\n meta_bytes = self._store[mkey]\n except KeyError:\n err_array_not_found(self._path)\n else:\n\n # decode and store metadata as instance members\n meta = decode_array_metadata(meta_bytes)\n self._meta = meta\n self._shape = meta['shape']\n self._chunks = meta['chunks']\n self._dtype = meta['dtype']\n self._fill_value = meta['fill_value']\n self._order = meta['order']\n\n # setup compressor\n config = meta['compressor']\n if config is None:\n self._compressor = None\n else:\n self._compressor = get_codec(config)\n\n # setup filters\n filters = meta['filters']\n if filters:\n filters = [get_codec(config) for config in filters]\n self._filters = filters\n\n def _refresh_metadata(self):\n if not self._cache_metadata:\n self._load_metadata()\n\n def _refresh_metadata_nosync(self):\n if not self._cache_metadata and not self._is_view:\n self._load_metadata_nosync()\n\n def _flush_metadata_nosync(self):\n if self._is_view:\n raise PermissionError('operation not permitted for views')\n\n if self._compressor:\n compressor_config = self._compressor.get_config()\n else:\n compressor_config = None\n if self._filters:\n filters_config = [f.get_config() for f in self._filters]\n else:\n filters_config = None\n meta = dict(shape=self._shape, chunks=self._chunks, dtype=self._dtype,\n compressor=compressor_config, fill_value=self._fill_value,\n order=self._order, filters=filters_config)\n mkey = self._key_prefix + array_meta_key\n self._store[mkey] = encode_array_metadata(meta)\n\n @property\n def store(self):\n \"\"\"A MutableMapping providing the underlying storage for the array.\"\"\"\n return self._store\n\n @property\n def path(self):\n \"\"\"Storage path.\"\"\"\n return self._path\n\n @property\n def name(self):\n \"\"\"Array name following h5py convention.\"\"\"\n if self.path:\n # follow h5py convention: add leading slash\n name = self.path\n if name[0] != '/':\n name = '/' + name\n return name\n return None\n\n @property\n def basename(self):\n \"\"\"Final component of name.\"\"\"\n if self.name is not None:\n return self.name.split('/')[-1]\n return None\n\n @property\n def read_only(self):\n \"\"\"A boolean, True if modification operations are not permitted.\"\"\"\n return self._read_only\n\n @read_only.setter\n def read_only(self, value):\n self._read_only = bool(value)\n\n @property\n def chunk_store(self):\n \"\"\"A MutableMapping providing the underlying storage for array chunks.\"\"\"\n if self._chunk_store is None:\n return self._store\n else:\n return self._chunk_store\n\n @property\n def shape(self):\n \"\"\"A tuple of integers describing the length of each dimension of\n the array.\"\"\"\n # N.B., shape may change if array is resized, hence need to refresh\n # metadata\n self._refresh_metadata()\n return self._shape\n\n @shape.setter\n def shape(self, value):\n self.resize(value)\n\n @property\n def chunks(self):\n \"\"\"A tuple of integers describing the length of each dimension of a\n chunk of the array.\"\"\"\n return self._chunks\n\n @property\n def dtype(self):\n \"\"\"The NumPy data type.\"\"\"\n return self._dtype\n\n @property\n def compressor(self):\n \"\"\"Primary compression codec.\"\"\"\n return self._compressor\n\n @property\n def fill_value(self):\n \"\"\"A value used for uninitialized portions of the array.\"\"\"\n return self._fill_value\n\n @property\n def order(self):\n \"\"\"A string indicating the order in which bytes are arranged within\n chunks of the array.\"\"\"\n return self._order\n\n @property\n def filters(self):\n \"\"\"One or more codecs used to transform data prior to compression.\"\"\"\n return self._filters\n\n @property\n def synchronizer(self):\n \"\"\"Object used to synchronize write access to the array.\"\"\"\n return self._synchronizer\n\n @property\n def attrs(self):\n \"\"\"A MutableMapping containing user-defined attributes. Note that\n attribute values must be JSON serializable.\"\"\"\n return self._attrs\n\n @property\n def ndim(self):\n \"\"\"Number of dimensions.\"\"\"\n return len(self.shape)\n\n @property\n def _size(self):\n return reduce(operator.mul, self._shape, 1)\n\n @property\n def size(self):\n \"\"\"The total number of elements in the array.\"\"\"\n # N.B., this property depends on shape, and shape may change if array\n # is resized, hence need to refresh metadata\n self._refresh_metadata()\n return self._size\n\n @property\n def itemsize(self):\n \"\"\"The size in bytes of each item in the array.\"\"\"\n return self.dtype.itemsize\n\n @property\n def _nbytes(self):\n return self._size * self.itemsize\n\n @property\n def nbytes(self):\n \"\"\"The total number of bytes that would be required to store the\n array without compression.\"\"\"\n # N.B., this property depends on shape, and shape may change if array\n # is resized, hence need to refresh metadata\n self._refresh_metadata()\n return self._nbytes\n\n @property\n def nbytes_stored(self):\n \"\"\"The total number of stored bytes of data for the array. This\n includes storage required for configuration metadata and user\n attributes.\"\"\"\n m = getsize(self._store, self._path)\n if self._chunk_store is None:\n return m\n else:\n n = getsize(self._chunk_store, self._path)\n if m < 0 or n < 0:\n return -1\n else:\n return m + n\n\n @property\n def _cdata_shape(self):\n if self._shape == ():\n return 1,\n else:\n return tuple(int(np.ceil(s / c))\n for s, c in zip(self._shape, self._chunks))\n\n @property\n def cdata_shape(self):\n \"\"\"A tuple of integers describing the number of chunks along each\n dimension of the array.\"\"\"\n self._refresh_metadata()\n return self._cdata_shape\n\n @property\n def _nchunks(self):\n return reduce(operator.mul, self._cdata_shape, 1)\n\n @property\n def nchunks(self):\n \"\"\"Total number of chunks.\"\"\"\n self._refresh_metadata()\n return self._nchunks\n\n @property\n def nchunks_initialized(self):\n \"\"\"The number of chunks that have been initialized with some data.\"\"\"\n\n # key pattern for chunk keys\n prog = re.compile(r'\\.'.join([r'\\d+'] * min(1, self.ndim)))\n\n # count chunk keys\n return sum(1 for k in listdir(self.chunk_store, self._path) if prog.match(k))\n\n # backwards compability\n initialized = nchunks_initialized\n\n @property\n def is_view(self):\n \"\"\"A boolean, True if this array is a view on another array.\"\"\"\n return self._is_view\n\n @property\n def oindex(self):\n \"\"\"Shortcut for orthogonal (outer) indexing, see :func:`get_orthogonal_selection` and\n :func:`set_orthogonal_selection` for documentation and examples.\"\"\"\n return self._oindex\n\n @property\n def vindex(self):\n \"\"\"Shortcut for vectorized (inner) indexing, see :func:`get_coordinate_selection`,\n :func:`set_coordinate_selection`, :func:`get_mask_selection` and\n :func:`set_mask_selection` for documentation and examples.\"\"\"\n return self._vindex\n\n def __eq__(self, other):\n return (\n isinstance(other, Array) and\n self.store == other.store and\n self.read_only == other.read_only and\n self.path == other.path and\n not self._is_view\n # N.B., no need to compare other properties, should be covered by\n # store comparison\n )\n\n def __array__(self, *args):\n a = self[...]\n if args:\n a = a.astype(args[0])\n return a\n\n def __len__(self):\n if self.shape:\n return self.shape[0]\n else:\n # 0-dimensional array, same error message as numpy\n raise TypeError('len() of unsized object')\n\n def __getitem__(self, selection):\n \"\"\"Retrieve data for an item or region of the array.\n\n Parameters\n ----------\n selection : tuple\n An integer index or slice or tuple of int/slice objects specifying the\n requested item or region for each dimension of the array.\n\n Returns\n -------\n out : ndarray\n A NumPy array containing the data for the requested region.\n\n Examples\n --------\n Setup a 1-dimensional array::\n\n >>> import zarr\n >>> import numpy as np\n >>> z = zarr.array(np.arange(100))\n\n Retrieve a single item::\n\n >>> z[5]\n 5\n\n Retrieve a region via slicing::\n\n >>> z[:5]\n array([0, 1, 2, 3, 4])\n >>> z[-5:]\n array([95, 96, 97, 98, 99])\n >>> z[5:10]\n array([5, 6, 7, 8, 9])\n >>> z[5:10:2]\n array([5, 7, 9])\n >>> z[::2]\n array([ 0, 2, 4, ..., 94, 96, 98])\n\n Load the entire array into memory::\n\n >>> z[...]\n array([ 0, 1, 2, ..., 97, 98, 99])\n\n Setup a 2-dimensional array::\n\n >>> z = zarr.array(np.arange(100).reshape(10, 10))\n\n Retrieve an item::\n\n >>> z[2, 2]\n 22\n\n Retrieve a region via slicing::\n\n >>> z[1:3, 1:3]\n array([[11, 12],\n [21, 22]])\n >>> z[1:3, :]\n array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],\n [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]])\n >>> z[:, 1:3]\n array([[ 1, 2],\n [11, 12],\n [21, 22],\n [31, 32],\n [41, 42],\n [51, 52],\n [61, 62],\n [71, 72],\n [81, 82],\n [91, 92]])\n >>> z[0:5:2, 0:5:2]\n array([[ 0, 2, 4],\n [20, 22, 24],\n [40, 42, 44]])\n >>> z[::2, ::2]\n array([[ 0, 2, 4, 6, 8],\n [20, 22, 24, 26, 28],\n [40, 42, 44, 46, 48],\n [60, 62, 64, 66, 68],\n [80, 82, 84, 86, 88]])\n\n Load the entire array into memory::\n\n >>> z[...]\n array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],\n [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],\n [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],\n [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],\n [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],\n [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],\n [70, 71, 72, 73, 74, 75, 76, 77, 78, 79],\n [80, 81, 82, 83, 84, 85, 86, 87, 88, 89],\n [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]])\n\n For arrays with a structured dtype, specific fields can be retrieved, e.g.::\n\n >>> a = np.array([(b'aaa', 1, 4.2),\n ... (b'bbb', 2, 8.4),\n ... (b'ccc', 3, 12.6)],\n ... dtype=[('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')])\n >>> z = zarr.array(a)\n >>> z['foo']\n array([b'aaa', b'bbb', b'ccc'],\n dtype='|S3')\n\n Notes\n -----\n Slices with step > 1 are supported, but slices with negative step are not.\n\n Currently the implementation for __getitem__ is provided by\n :func:`get_basic_selection`. For advanced (\"fancy\") indexing, see the methods\n listed under See Also.\n\n See Also\n --------\n get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection,\n get_coordinate_selection, set_coordinate_selection, get_orthogonal_selection,\n set_orthogonal_selection, vindex, oindex, __setitem__\n\n \"\"\"\n\n fields, selection = pop_fields(selection)\n return self.get_basic_selection(selection, fields=fields)\n\n def get_basic_selection(self, selection=Ellipsis, out=None, fields=None):\n \"\"\"Retrieve data for an item or region of the array.\n\n Parameters\n ----------\n selection : tuple\n A tuple specifying the requested item or region for each dimension of the\n array. May be any combination of int and/or slice for multidimensional arrays.\n out : ndarray, optional\n If given, load the selected data directly into this array.\n fields : str or sequence of str, optional\n For arrays with a structured dtype, one or more fields can be specified to\n extract data for.\n\n Returns\n -------\n out : ndarray\n A NumPy array containing the data for the requested region.\n\n Examples\n --------\n Setup a 1-dimensional array::\n\n >>> import zarr\n >>> import numpy as np\n >>> z = zarr.array(np.arange(100))\n\n Retrieve a single item::\n\n >>> z.get_basic_selection(5)\n 5\n\n Retrieve a region via slicing::\n\n >>> z.get_basic_selection(slice(5))\n array([0, 1, 2, 3, 4])\n >>> z.get_basic_selection(slice(-5, None))\n array([95, 96, 97, 98, 99])\n >>> z.get_basic_selection(slice(5, 10))\n array([5, 6, 7, 8, 9])\n >>> z.get_basic_selection(slice(5, 10, 2))\n array([5, 7, 9])\n >>> z.get_basic_selection(slice(None, None, 2))\n array([ 0, 2, 4, ..., 94, 96, 98])\n\n Setup a 2-dimensional array::\n\n >>> z = zarr.array(np.arange(100).reshape(10, 10))\n\n Retrieve an item::\n\n >>> z.get_basic_selection((2, 2))\n 22\n\n Retrieve a region via slicing::\n\n >>> z.get_basic_selection((slice(1, 3), slice(1, 3)))\n array([[11, 12],\n [21, 22]])\n >>> z.get_basic_selection((slice(1, 3), slice(None)))\n array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],\n [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]])\n >>> z.get_basic_selection((slice(None), slice(1, 3)))\n array([[ 1, 2],\n [11, 12],\n [21, 22],\n [31, 32],\n [41, 42],\n [51, 52],\n [61, 62],\n [71, 72],\n [81, 82],\n [91, 92]])\n >>> z.get_basic_selection((slice(0, 5, 2), slice(0, 5, 2)))\n array([[ 0, 2, 4],\n [20, 22, 24],\n [40, 42, 44]])\n >>> z.get_basic_selection((slice(None, None, 2), slice(None, None, 2)))\n array([[ 0, 2, 4, 6, 8],\n [20, 22, 24, 26, 28],\n [40, 42, 44, 46, 48],\n [60, 62, 64, 66, 68],\n [80, 82, 84, 86, 88]])\n\n For arrays with a structured dtype, specific fields can be retrieved, e.g.::\n\n >>> a = np.array([(b'aaa', 1, 4.2),\n ... (b'bbb', 2, 8.4),\n ... (b'ccc', 3, 12.6)],\n ... dtype=[('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')])\n >>> z = zarr.array(a)\n >>> z.get_basic_selection(slice(2), fields='foo')\n array([b'aaa', b'bbb'],\n dtype='|S3')\n\n Notes\n -----\n Slices with step > 1 are supported, but slices with negative step are not.\n\n Currently this method provides the implementation for accessing data via the\n square bracket notation (__getitem__). See :func:`__getitem__` for examples\n using the alternative notation.\n\n See Also\n --------\n set_basic_selection, get_mask_selection, set_mask_selection,\n get_coordinate_selection, set_coordinate_selection, get_orthogonal_selection,\n set_orthogonal_selection, vindex, oindex, __getitem__, __setitem__\n\n \"\"\"\n\n # refresh metadata\n if not self._cache_metadata:\n self._load_metadata()\n\n # check args\n check_fields(fields, self._dtype)\n\n # handle zero-dimensional arrays\n if self._shape == ():\n return self._get_basic_selection_zd(selection=selection, out=out,\n fields=fields)\n else:\n return self._get_basic_selection_nd(selection=selection, out=out,\n fields=fields)\n\n def _get_basic_selection_zd(self, selection, out=None, fields=None):\n # special case basic selection for zero-dimensional array\n\n # check selection is valid\n selection = ensure_tuple(selection)\n if selection not in ((), (Ellipsis,)):\n err_too_many_indices(selection, ())\n\n try:\n # obtain encoded data for chunk\n ckey = self._chunk_key((0,))\n cdata = self.chunk_store[ckey]\n\n except KeyError:\n # chunk not initialized\n chunk = np.zeros((), dtype=self._dtype)\n if self._fill_value is not None:\n chunk.fill(self._fill_value)\n\n else:\n chunk = self._decode_chunk(cdata)\n\n # handle fields\n if fields:\n chunk = chunk[fields]\n\n # handle selection of the scalar value via empty tuple\n if out is None:\n out = chunk[selection]\n else:\n out[selection] = chunk[selection]\n\n return out\n\n def _get_basic_selection_nd(self, selection, out=None, fields=None):\n # implementation of basic selection for array with at least one dimension\n\n # setup indexer\n indexer = BasicIndexer(selection, self)\n\n return self._get_selection(indexer=indexer, out=out, fields=fields)\n\n def get_orthogonal_selection(self, selection, out=None, fields=None):\n \"\"\"Retrieve data by making a selection for each dimension of the array. For\n example, if an array has 2 dimensions, allows selecting specific rows and/or\n columns. The selection for each dimension can be either an integer (indexing a\n single item), a slice, an array of integers, or a Boolean array where True\n values indicate a selection.\n\n Parameters\n ----------\n selection : tuple\n A selection for each dimension of the array. May be any combination of int,\n slice, integer array or Boolean array.\n out : ndarray, optional\n If given, load the selected data directly into this array.\n fields : str or sequence of str, optional\n For arrays with a structured dtype, one or more fields can be specified to\n extract data for.\n\n Returns\n -------\n out : ndarray\n A NumPy array containing the data for the requested selection.\n\n Examples\n --------\n Setup a 2-dimensional array::\n\n >>> import zarr\n >>> import numpy as np\n >>> z = zarr.array(np.arange(100).reshape(10, 10))\n\n Retrieve rows and columns via any combination of int, slice, integer array and/or\n Boolean array::\n\n >>> z.get_orthogonal_selection(([1, 4], slice(None)))\n array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],\n [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]])\n >>> z.get_orthogonal_selection((slice(None), [1, 4]))\n array([[ 1, 4],\n [11, 14],\n [21, 24],\n [31, 34],\n [41, 44],\n [51, 54],\n [61, 64],\n [71, 74],\n [81, 84],\n [91, 94]])\n >>> z.get_orthogonal_selection(([1, 4], [1, 4]))\n array([[11, 14],\n [41, 44]])\n >>> sel = np.zeros(z.shape[0], dtype=bool)\n >>> sel[1] = True\n >>> sel[4] = True\n >>> z.get_orthogonal_selection((sel, sel))\n array([[11, 14],\n [41, 44]])\n\n For convenience, the orthogonal selection functionality is also available via the\n `oindex` property, e.g.::\n\n >>> z.oindex[[1, 4], :]\n array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],\n [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]])\n >>> z.oindex[:, [1, 4]]\n array([[ 1, 4],\n [11, 14],\n [21, 24],\n [31, 34],\n [41, 44],\n [51, 54],\n [61, 64],\n [71, 74],\n [81, 84],\n [91, 94]])\n >>> z.oindex[[1, 4], [1, 4]]\n array([[11, 14],\n [41, 44]])\n >>> sel = np.zeros(z.shape[0], dtype=bool)\n >>> sel[1] = True\n >>> sel[4] = True\n >>> z.oindex[sel, sel]\n array([[11, 14],\n [41, 44]])\n\n Notes\n -----\n Orthogonal indexing is also known as outer indexing.\n\n Slices with step > 1 are supported, but slices with negative step are not.\n\n See Also\n --------\n get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection,\n get_coordinate_selection, set_coordinate_selection, set_orthogonal_selection,\n vindex, oindex, __getitem__, __setitem__\n\n \"\"\"\n\n # refresh metadata\n if not self._cache_metadata:\n self._load_metadata()\n\n # check args\n check_fields(fields, self._dtype)\n\n # setup indexer\n indexer = OrthogonalIndexer(selection, self)\n\n return self._get_selection(indexer=indexer, out=out, fields=fields)\n\n def get_coordinate_selection(self, selection, out=None, fields=None):\n \"\"\"Retrieve a selection of individual items, by providing the indices\n (coordinates) for each selected item.\n\n Parameters\n ----------\n selection : tuple\n An integer (coordinate) array for each dimension of the array.\n out : ndarray, optional\n If given, load the selected data directly into this array.\n fields : str or sequence of str, optional\n For arrays with a structured dtype, one or more fields can be specified to\n extract data for.\n\n Returns\n -------\n out : ndarray\n A NumPy array containing the data for the requested selection.\n\n Examples\n --------\n Setup a 2-dimensional array::\n\n >>> import zarr\n >>> import numpy as np\n >>> z = zarr.array(np.arange(100).reshape(10, 10))\n\n Retrieve items by specifying their coordinates::\n\n >>> z.get_coordinate_selection(([1, 4], [1, 4]))\n array([11, 44])\n\n For convenience, the coordinate selection functionality is also available via the\n `vindex` property, e.g.::\n\n >>> z.vindex[[1, 4], [1, 4]]\n array([11, 44])\n\n Notes\n -----\n Coordinate indexing is also known as point selection, and is a form of vectorized\n or inner indexing.\n\n Slices are not supported. Coordinate arrays must be provided for all dimensions\n of the array.\n\n Coordinate arrays may be multidimensional, in which case the output array will\n also be multidimensional. Coordinate arrays are broadcast against each other\n before being applied. The shape of the output will be the same as the shape of\n each coordinate array after broadcasting.\n\n See Also\n --------\n get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection,\n get_orthogonal_selection, set_orthogonal_selection, set_coordinate_selection,\n vindex, oindex, __getitem__, __setitem__\n\n \"\"\"\n\n # refresh metadata\n if not self._cache_metadata:\n self._load_metadata()\n\n # check args\n check_fields(fields, self._dtype)\n\n # setup indexer\n indexer = CoordinateIndexer(selection, self)\n\n # handle output - need to flatten\n if out is not None:\n out = out.reshape(-1)\n\n out = self._get_selection(indexer=indexer, out=out, fields=fields)\n\n # restore shape\n out = out.reshape(indexer.sel_shape)\n\n return out\n\n def get_mask_selection(self, selection, out=None, fields=None):\n \"\"\"Retrieve a selection of individual items, by providing a Boolean array of the\n same shape as the array against which the selection is being made, where True\n values indicate a selected item.\n\n Parameters\n ----------\n selection : ndarray, bool\n A Boolean array of the same shape as the array against which the selection is\n being made.\n out : ndarray, optional\n If given, load the selected data directly into this array.\n fields : str or sequence of str, optional\n For arrays with a structured dtype, one or more fields can be specified to\n extract data for.\n\n Returns\n -------\n out : ndarray\n A NumPy array containing the data for the requested selection.\n\n Examples\n --------\n Setup a 2-dimensional array::\n\n >>> import zarr\n >>> import numpy as np\n >>> z = zarr.array(np.arange(100).reshape(10, 10))\n\n Retrieve items by specifying a maks::\n\n >>> sel = np.zeros_like(z, dtype=bool)\n >>> sel[1, 1] = True\n >>> sel[4, 4] = True\n >>> z.get_mask_selection(sel)\n array([11, 44])\n\n For convenience, the mask selection functionality is also available via the\n `vindex` property, e.g.::\n\n >>> z.vindex[sel]\n array([11, 44])\n\n Notes\n -----\n Mask indexing is a form of vectorized or inner indexing, and is equivalent to\n coordinate indexing. Internally the mask array is converted to coordinate\n arrays by calling `np.nonzero`.\n\n See Also\n --------\n get_basic_selection, set_basic_selection, set_mask_selection,\n get_orthogonal_selection, set_orthogonal_selection, get_coordinate_selection,\n set_coordinate_selection, vindex, oindex, __getitem__, __setitem__\n\n \"\"\"\n\n # refresh metadata\n if not self._cache_metadata:\n self._load_metadata()\n\n # check args\n check_fields(fields, self._dtype)\n\n # setup indexer\n indexer = MaskIndexer(selection, self)\n\n return self._get_selection(indexer=indexer, out=out, fields=fields)\n\n def _get_selection(self, indexer, out=None, fields=None):\n\n # We iterate over all chunks which overlap the selection and thus contain data\n # that needs to be extracted. Each chunk is processed in turn, extracting the\n # necessary data and storing into the correct location in the output array.\n\n # N.B., it is an important optimisation that we only visit chunks which overlap\n # the selection. This minimises the number of iterations in the main for loop.\n\n # check fields are sensible\n out_dtype = check_fields(fields, self._dtype)\n\n # determine output shape\n out_shape = indexer.shape\n\n # setup output array\n if out is None:\n out = np.empty(out_shape, dtype=out_dtype, order=self._order)\n else:\n check_array_shape('out', out, out_shape)\n\n # iterate over chunks\n for chunk_coords, chunk_selection, out_selection in indexer:\n\n # load chunk selection into output array\n self._chunk_getitem(chunk_coords, chunk_selection, out, out_selection,\n drop_axes=indexer.drop_axes, fields=fields)\n\n if out.shape:\n return out\n else:\n return out[()]\n\n def __setitem__(self, selection, value):\n \"\"\"Modify data for an item or region of the array.\n\n Parameters\n ----------\n selection : tuple\n An integer index or slice or tuple of int/slice specifying the requested\n region for each dimension of the array.\n value : scalar or array-like\n Value to be stored into the array.\n\n Examples\n --------\n Setup a 1-dimensional array::\n\n >>> import zarr\n >>> z = zarr.zeros(100, dtype=int)\n\n Set all array elements to the same scalar value::\n\n >>> z[...] = 42\n >>> z[...]\n array([42, 42, 42, ..., 42, 42, 42])\n\n Set a portion of the array::\n\n >>> z[:10] = np.arange(10)\n >>> z[-10:] = np.arange(10)[::-1]\n >>> z[...]\n array([ 0, 1, 2, ..., 2, 1, 0])\n\n Setup a 2-dimensional array::\n\n >>> z = zarr.zeros((5, 5), dtype=int)\n\n Set all array elements to the same scalar value::\n\n >>> z[...] = 42\n\n Set a portion of the array::\n\n >>> z[0, :] = np.arange(z.shape[1])\n >>> z[:, 0] = np.arange(z.shape[0])\n >>> z[...]\n array([[ 0, 1, 2, 3, 4],\n [ 1, 42, 42, 42, 42],\n [ 2, 42, 42, 42, 42],\n [ 3, 42, 42, 42, 42],\n [ 4, 42, 42, 42, 42]])\n\n For arrays with a structured dtype, specific fields can be modified, e.g.::\n\n >>> a = np.array([(b'aaa', 1, 4.2),\n ... (b'bbb', 2, 8.4),\n ... (b'ccc', 3, 12.6)],\n ... dtype=[('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')])\n >>> z = zarr.array(a)\n >>> z['foo'] = b'zzz'\n >>> z[...]\n array([(b'zzz', 1, 4.2), (b'zzz', 2, 8.4), (b'zzz', 3, 12.6)],\n dtype=[('foo', 'S3'), ('bar', '<i4'), ('baz', '<f8')])\n\n Notes\n -----\n Slices with step > 1 are supported, but slices with negative step are not.\n\n Currently the implementation for __setitem__ is provided by\n :func:`set_basic_selection`, which means that only integers and slices are\n supported within the selection. For advanced (\"fancy\") indexing, see the\n methods listed under See Also.\n\n See Also\n --------\n get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection,\n get_coordinate_selection, set_coordinate_selection, get_orthogonal_selection,\n set_orthogonal_selection, vindex, oindex, __getitem__\n\n \"\"\"\n\n fields, selection = pop_fields(selection)\n self.set_basic_selection(selection, value, fields=fields)\n\n def set_basic_selection(self, selection, value, fields=None):\n \"\"\"Modify data for an item or region of the array.\n\n Parameters\n ----------\n selection : tuple\n An integer index or slice or tuple of int/slice specifying the requested\n region for each dimension of the array.\n value : scalar or array-like\n Value to be stored into the array.\n fields : str or sequence of str, optional\n For arrays with a structured dtype, one or more fields can be specified to set\n data for.\n\n Examples\n --------\n Setup a 1-dimensional array::\n\n >>> import zarr\n >>> import numpy as np\n >>> z = zarr.zeros(100, dtype=int)\n\n Set all array elements to the same scalar value::\n\n >>> z.set_basic_selection(..., 42)\n >>> z[...]\n array([42, 42, 42, ..., 42, 42, 42])\n\n Set a portion of the array::\n\n >>> z.set_basic_selection(slice(10), np.arange(10))\n >>> z.set_basic_selection(slice(-10, None), np.arange(10)[::-1])\n >>> z[...]\n array([ 0, 1, 2, ..., 2, 1, 0])\n\n Setup a 2-dimensional array::\n\n >>> z = zarr.zeros((5, 5), dtype=int)\n\n Set all array elements to the same scalar value::\n\n >>> z.set_basic_selection(..., 42)\n\n Set a portion of the array::\n\n >>> z.set_basic_selection((0, slice(None)), np.arange(z.shape[1]))\n >>> z.set_basic_selection((slice(None), 0), np.arange(z.shape[0]))\n >>> z[...]\n array([[ 0, 1, 2, 3, 4],\n [ 1, 42, 42, 42, 42],\n [ 2, 42, 42, 42, 42],\n [ 3, 42, 42, 42, 42],\n [ 4, 42, 42, 42, 42]])\n\n For arrays with a structured dtype, the `fields` parameter can be used to set\n data for a specific field, e.g.::\n\n >>> a = np.array([(b'aaa', 1, 4.2),\n ... (b'bbb', 2, 8.4),\n ... (b'ccc', 3, 12.6)],\n ... dtype=[('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')])\n >>> z = zarr.array(a)\n >>> z.set_basic_selection(slice(0, 2), b'zzz', fields='foo')\n >>> z[:]\n array([(b'zzz', 1, 4.2), (b'zzz', 2, 8.4), (b'ccc', 3, 12.6)],\n dtype=[('foo', 'S3'), ('bar', '<i4'), ('baz', '<f8')])\n\n Notes\n -----\n This method provides the underlying implementation for modifying data via square\n bracket notation, see :func:`__setitem__` for equivalent examples using the\n alternative notation.\n\n See Also\n --------\n get_basic_selection, get_mask_selection, set_mask_selection,\n get_coordinate_selection, set_coordinate_selection, get_orthogonal_selection,\n set_orthogonal_selection, vindex, oindex, __getitem__, __setitem__\n\n \"\"\"\n\n # guard conditions\n if self._read_only:\n err_read_only()\n\n # refresh metadata\n if not self._cache_metadata:\n self._load_metadata_nosync()\n\n # handle zero-dimensional arrays\n if self._shape == ():\n return self._set_basic_selection_zd(selection, value, fields=fields)\n else:\n return self._set_basic_selection_nd(selection, value, fields=fields)\n\n def set_orthogonal_selection(self, selection, value, fields=None):\n \"\"\"Modify data via a selection for each dimension of the array.\n\n Parameters\n ----------\n selection : tuple\n A selection for each dimension of the array. May be any combination of int,\n slice, integer array or Boolean array.\n value : scalar or array-like\n Value to be stored into the array.\n fields : str or sequence of str, optional\n For arrays with a structured dtype, one or more fields can be specified to set\n data for.\n\n Examples\n --------\n Setup a 2-dimensional array::\n\n >>> import zarr\n >>> import numpy as np\n >>> z = zarr.zeros((5, 5), dtype=int)\n\n Set data for a selection of rows::\n\n >>> z.set_orthogonal_selection(([1, 4], slice(None)), 1)\n >>> z[...]\n array([[0, 0, 0, 0, 0],\n [1, 1, 1, 1, 1],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [1, 1, 1, 1, 1]])\n\n Set data for a selection of columns::\n\n >>> z.set_orthogonal_selection((slice(None), [1, 4]), 2)\n >>> z[...]\n array([[0, 2, 0, 0, 2],\n [1, 2, 1, 1, 2],\n [0, 2, 0, 0, 2],\n [0, 2, 0, 0, 2],\n [1, 2, 1, 1, 2]])\n\n Set data for a selection of rows and columns::\n\n >>> z.set_orthogonal_selection(([1, 4], [1, 4]), 3)\n >>> z[...]\n array([[0, 2, 0, 0, 2],\n [1, 3, 1, 1, 3],\n [0, 2, 0, 0, 2],\n [0, 2, 0, 0, 2],\n [1, 3, 1, 1, 3]])\n\n For convenience, this functionality is also available via the `oindex` property.\n E.g.::\n\n >>> z.oindex[[1, 4], [1, 4]] = 4\n >>> z[...]\n array([[0, 2, 0, 0, 2],\n [1, 4, 1, 1, 4],\n [0, 2, 0, 0, 2],\n [0, 2, 0, 0, 2],\n [1, 4, 1, 1, 4]])\n\n Notes\n -----\n Orthogonal indexing is also known as outer indexing.\n\n Slices with step > 1 are supported, but slices with negative step are not.\n\n See Also\n --------\n get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection,\n get_coordinate_selection, set_coordinate_selection, get_orthogonal_selection,\n vindex, oindex, __getitem__, __setitem__\n\n \"\"\"\n\n # guard conditions\n if self._read_only:\n err_read_only()\n\n # refresh metadata\n if not self._cache_metadata:\n self._load_metadata_nosync()\n\n # setup indexer\n indexer = OrthogonalIndexer(selection, self)\n\n self._set_selection(indexer, value, fields=fields)\n\n def set_coordinate_selection(self, selection, value, fields=None):\n \"\"\"Modify a selection of individual items, by providing the indices (coordinates)\n for each item to be modified.\n\n Parameters\n ----------\n selection : tuple\n An integer (coordinate) array for each dimension of the array.\n value : scalar or array-like\n Value to be stored into the array.\n fields : str or sequence of str, optional\n For arrays with a structured dtype, one or more fields can be specified to set\n data for.\n\n Examples\n --------\n Setup a 2-dimensional array::\n\n >>> import zarr\n >>> import numpy as np\n >>> z = zarr.zeros((5, 5), dtype=int)\n\n Set data for a selection of items::\n\n >>> z.set_coordinate_selection(([1, 4], [1, 4]), 1)\n >>> z[...]\n array([[0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1]])\n\n For convenience, this functionality is also available via the `vindex` property.\n E.g.::\n\n >>> z.vindex[[1, 4], [1, 4]] = 2\n >>> z[...]\n array([[0, 0, 0, 0, 0],\n [0, 2, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 2]])\n\n Notes\n -----\n Coordinate indexing is also known as point selection, and is a form of vectorized\n or inner indexing.\n\n Slices are not supported. Coordinate arrays must be provided for all dimensions\n of the array.\n\n See Also\n --------\n get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection,\n get_orthogonal_selection, set_orthogonal_selection, get_coordinate_selection,\n vindex, oindex, __getitem__, __setitem__\n\n \"\"\"\n\n # guard conditions\n if self._read_only:\n err_read_only()\n\n # refresh metadata\n if not self._cache_metadata:\n self._load_metadata_nosync()\n\n # setup indexer\n indexer = CoordinateIndexer(selection, self)\n\n # handle value - need to flatten\n if not is_scalar(value, self._dtype):\n value = np.asanyarray(value)\n if hasattr(value, 'shape') and len(value.shape) > 1:\n value = value.reshape(-1)\n\n self._set_selection(indexer, value, fields=fields)\n\n def set_mask_selection(self, selection, value, fields=None):\n \"\"\"Modify a selection of individual items, by providing a Boolean array of the\n same shape as the array against which the selection is being made, where True\n values indicate a selected item.\n\n Parameters\n ----------\n selection : ndarray, bool\n A Boolean array of the same shape as the array against which the selection is\n being made.\n value : scalar or array-like\n Value to be stored into the array.\n fields : str or sequence of str, optional\n For arrays with a structured dtype, one or more fields can be specified to set\n data for.\n\n Examples\n --------\n Setup a 2-dimensional array::\n\n >>> import zarr\n >>> import numpy as np\n >>> z = zarr.zeros((5, 5), dtype=int)\n\n Set data for a selection of items::\n\n >>> sel = np.zeros_like(z, dtype=bool)\n >>> sel[1, 1] = True\n >>> sel[4, 4] = True\n >>> z.set_mask_selection(sel, 1)\n >>> z[...]\n array([[0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1]])\n\n For convenience, this functionality is also available via the `vindex` property.\n E.g.::\n\n >>> z.vindex[sel] = 2\n >>> z[...]\n array([[0, 0, 0, 0, 0],\n [0, 2, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 2]])\n\n Notes\n -----\n Mask indexing is a form of vectorized or inner indexing, and is equivalent to\n coordinate indexing. Internally the mask array is converted to coordinate\n arrays by calling `np.nonzero`.\n\n See Also\n --------\n get_basic_selection, set_basic_selection, get_mask_selection,\n get_orthogonal_selection, set_orthogonal_selection, get_coordinate_selection,\n set_coordinate_selection, vindex, oindex, __getitem__, __setitem__\n\n \"\"\"\n\n # guard conditions\n if self._read_only:\n err_read_only()\n\n # refresh metadata\n if not self._cache_metadata:\n self._load_metadata_nosync()\n\n # setup indexer\n indexer = MaskIndexer(selection, self)\n\n self._set_selection(indexer, value, fields=fields)\n\n def _set_basic_selection_zd(self, selection, value, fields=None):\n # special case __setitem__ for zero-dimensional array\n\n # check selection is valid\n selection = ensure_tuple(selection)\n if selection not in ((), (Ellipsis,)):\n err_too_many_indices(selection, self._shape)\n\n # check fields\n check_fields(fields, self._dtype)\n fields = check_no_multi_fields(fields)\n\n # obtain key for chunk\n ckey = self._chunk_key((0,))\n\n # setup chunk\n try:\n # obtain compressed data for chunk\n cdata = self.chunk_store[ckey]\n\n except KeyError:\n # chunk not initialized\n chunk = np.zeros((), dtype=self._dtype)\n if self._fill_value is not None:\n chunk.fill(self._fill_value)\n\n else:\n # decode chunk\n chunk = self._decode_chunk(cdata).copy()\n\n # set value\n if fields:\n chunk[fields][selection] = value\n else:\n chunk[selection] = value\n\n # encode and store\n cdata = self._encode_chunk(chunk)\n self.chunk_store[ckey] = cdata\n\n def _set_basic_selection_nd(self, selection, value, fields=None):\n # implementation of __setitem__ for array with at least one dimension\n\n # setup indexer\n indexer = BasicIndexer(selection, self)\n\n self._set_selection(indexer, value, fields=fields)\n\n def _set_selection(self, indexer, value, fields=None):\n\n # We iterate over all chunks which overlap the selection and thus contain data\n # that needs to be replaced. Each chunk is processed in turn, extracting the\n # necessary data from the value array and storing into the chunk array.\n\n # N.B., it is an important optimisation that we only visit chunks which overlap\n # the selection. This minimises the nuimber of iterations in the main for loop.\n\n # check fields are sensible\n check_fields(fields, self._dtype)\n fields = check_no_multi_fields(fields)\n\n # determine indices of chunks overlapping the selection\n sel_shape = indexer.shape\n\n # check value shape\n if sel_shape == ():\n # setting a single item\n pass\n elif is_scalar(value, self._dtype):\n # setting a scalar value\n pass\n else:\n if not hasattr(value, 'shape'):\n value = np.asanyarray(value)\n check_array_shape('value', value, sel_shape)\n\n # iterate over chunks in range\n for chunk_coords, chunk_selection, out_selection in indexer:\n\n # extract data to store\n if sel_shape == ():\n chunk_value = value\n elif is_scalar(value, self._dtype):\n chunk_value = value\n else:\n chunk_value = value[out_selection]\n # handle missing singleton dimensions\n if indexer.drop_axes:\n item = [slice(None)] * self.ndim\n for a in indexer.drop_axes:\n item[a] = np.newaxis\n chunk_value = chunk_value[item]\n\n # put data\n self._chunk_setitem(chunk_coords, chunk_selection, chunk_value, fields=fields)\n\n def _chunk_getitem(self, chunk_coords, chunk_selection, out, out_selection,\n drop_axes=None, fields=None):\n \"\"\"Obtain part or whole of a chunk.\n\n Parameters\n ----------\n chunk_coords : tuple of ints\n Indices of the chunk.\n chunk_selection : selection\n Location of region within the chunk to extract.\n out : ndarray\n Array to store result in.\n out_selection : selection\n Location of region within output array to store results in.\n drop_axes : tuple of ints\n Axes to squeeze out of the chunk.\n fields\n TODO\n\n \"\"\"\n\n assert len(chunk_coords) == len(self._cdata_shape)\n\n # obtain key for chunk\n ckey = self._chunk_key(chunk_coords)\n\n try:\n # obtain compressed data for chunk\n cdata = self.chunk_store[ckey]\n\n except KeyError:\n # chunk not initialized\n if self._fill_value is not None:\n out[out_selection] = self._fill_value\n\n else:\n\n if (isinstance(out, np.ndarray) and\n not fields and\n is_contiguous_selection(out_selection) and\n is_total_slice(chunk_selection, self._chunks) and\n not self._filters and\n self._dtype != object):\n\n dest = out[out_selection]\n write_direct = (\n dest.flags.writeable and (\n (self._order == 'C' and dest.flags.c_contiguous) or\n (self._order == 'F' and dest.flags.f_contiguous)\n )\n )\n\n if write_direct:\n\n # optimization: we want the whole chunk, and the destination is\n # contiguous, so we can decompress directly from the chunk\n # into the destination array\n\n if self._compressor:\n self._compressor.decode(cdata, dest)\n else:\n if isinstance(cdata, np.ndarray):\n chunk = cdata.view(self._dtype)\n else:\n chunk = np.frombuffer(cdata, dtype=self._dtype)\n chunk = chunk.reshape(self._chunks, order=self._order)\n np.copyto(dest, chunk)\n return\n\n # decode chunk\n chunk = self._decode_chunk(cdata)\n\n # select data from chunk\n if fields:\n chunk = chunk[fields]\n tmp = chunk[chunk_selection]\n if drop_axes:\n tmp = np.squeeze(tmp, axis=drop_axes)\n\n # store selected data in output\n out[out_selection] = tmp\n\n def _chunk_setitem(self, chunk_coords, chunk_selection, value, fields=None):\n \"\"\"Replace part or whole of a chunk.\n\n Parameters\n ----------\n chunk_coords : tuple of ints\n Indices of the chunk.\n chunk_selection : tuple of slices\n Location of region within the chunk.\n value : scalar or ndarray\n Value to set.\n\n \"\"\"\n\n if self._synchronizer is None:\n # no synchronization\n lock = nolock\n else:\n # synchronize on the chunk\n ckey = self._chunk_key(chunk_coords)\n lock = self._synchronizer[ckey]\n\n with lock:\n self._chunk_setitem_nosync(chunk_coords, chunk_selection, value,\n fields=fields)\n\n def _chunk_setitem_nosync(self, chunk_coords, chunk_selection, value, fields=None):\n\n # obtain key for chunk storage\n ckey = self._chunk_key(chunk_coords)\n\n if is_total_slice(chunk_selection, self._chunks) and not fields:\n # totally replace chunk\n\n # optimization: we are completely replacing the chunk, so no need\n # to access the existing chunk data\n\n if is_scalar(value, self._dtype):\n\n # setup array filled with value\n chunk = np.empty(self._chunks, dtype=self._dtype, order=self._order)\n chunk.fill(value)\n\n else:\n\n if not self._compressor and not self._filters:\n\n # https://github.com/alimanfoo/zarr/issues/79\n # Ensure a copy is taken so we don't end up storing\n # a view into someone else's array.\n # N.B., this assumes that filters or compressor always\n # take a copy and never attempt to apply encoding in-place.\n chunk = np.array(value, dtype=self._dtype, order=self._order)\n\n else:\n # ensure array is contiguous\n if self._order == 'F':\n chunk = np.asfortranarray(value, dtype=self._dtype)\n else:\n chunk = np.ascontiguousarray(value, dtype=self._dtype)\n\n else:\n # partially replace the contents of this chunk\n\n try:\n\n # obtain compressed data for chunk\n cdata = self.chunk_store[ckey]\n\n except KeyError:\n\n # chunk not initialized\n if self._fill_value is not None:\n chunk = np.empty(self._chunks, dtype=self._dtype, order=self._order)\n chunk.fill(self._fill_value)\n elif self._dtype == object:\n chunk = np.empty(self._chunks, dtype=self._dtype, order=self._order)\n else:\n # N.B., use zeros here so any region beyond the array has consistent\n # and compressible data\n chunk = np.zeros(self._chunks, dtype=self._dtype, order=self._order)\n\n else:\n\n # decode chunk\n chunk = self._decode_chunk(cdata)\n if not chunk.flags.writeable:\n chunk = chunk.copy(order='K')\n\n # modify\n if fields:\n # N.B., currently multi-field assignment is not supported in numpy, so\n # this only works for a single field\n chunk[fields][chunk_selection] = value\n else:\n chunk[chunk_selection] = value\n\n # encode chunk\n cdata = self._encode_chunk(chunk)\n\n # store\n self.chunk_store[ckey] = cdata\n\n def _chunk_key(self, chunk_coords):\n return self._key_prefix + '.'.join(map(str, chunk_coords))\n\n def _decode_chunk(self, cdata):\n\n # decompress\n if self._compressor:\n chunk = self._compressor.decode(cdata)\n else:\n chunk = cdata\n\n # apply filters\n if self._filters:\n for f in self._filters[::-1]:\n chunk = f.decode(chunk)\n\n # view as correct dtype\n if self._dtype == object:\n if isinstance(chunk, np.ndarray):\n chunk = chunk.astype(self._dtype)\n else:\n raise RuntimeError('cannot read object array without object codec')\n elif isinstance(chunk, np.ndarray):\n chunk = chunk.view(self._dtype)\n else:\n chunk = np.frombuffer(chunk, dtype=self._dtype)\n\n # reshape\n chunk = chunk.reshape(self._chunks, order=self._order)\n\n return chunk\n\n def _encode_chunk(self, chunk):\n\n # apply filters\n if self._filters:\n for f in self._filters:\n chunk = f.encode(chunk)\n\n # check object encoding\n if isinstance(chunk, np.ndarray) and chunk.dtype == object:\n raise RuntimeError('cannot write object array without object codec')\n\n # compress\n if self._compressor:\n cdata = self._compressor.encode(chunk)\n else:\n cdata = chunk\n\n return cdata\n\n def __repr__(self):\n t = type(self)\n r = '<%s.%s' % (t.__module__, t.__name__)\n if self.name:\n r += ' %r' % self.name\n r += ' %s' % str(self.shape)\n r += ' %s' % self.dtype\n if self._read_only:\n r += ' read-only'\n r += '>'\n return r\n\n @property\n def info(self):\n \"\"\"Report some diagnostic information about the array.\n\n Examples\n --------\n >>> import zarr\n >>> z = zarr.zeros(1000000, chunks=100000, dtype='i4')\n >>> z.info\n Type : zarr.core.Array\n Data type : int32\n Shape : (1000000,)\n Chunk shape : (100000,)\n Order : C\n Read-only : False\n Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)\n Store type : builtins.dict\n No. bytes : 4000000 (3.8M)\n No. bytes stored : ...\n Storage ratio : ...\n Chunks initialized : 0/10\n\n \"\"\"\n return self._info_reporter\n\n def info_items(self):\n return self._synchronized_op(self._info_items_nosync)\n\n def _info_items_nosync(self):\n\n def typestr(o):\n return '%s.%s' % (type(o).__module__, type(o).__name__)\n\n def bytestr(n):\n if n > 2**10:\n return '%s (%s)' % (n, human_readable_size(n))\n else:\n return str(n)\n\n items = []\n\n # basic info\n if self.name is not None:\n items += [('Name', self.name)]\n items += [\n ('Type', typestr(self)),\n ('Data type', '%s' % self.dtype),\n ('Shape', str(self.shape)),\n ('Chunk shape', str(self.chunks)),\n ('Order', self.order),\n ('Read-only', str(self.read_only)),\n ]\n\n # filters\n if self.filters:\n for i, f in enumerate(self.filters):\n items += [('Filter [%s]' % i, repr(f))]\n\n # compressor\n items += [('Compressor', repr(self.compressor))]\n\n # synchronizer\n if self._synchronizer is not None:\n items += [('Synchronizer type', typestr(self._synchronizer))]\n\n # storage info\n items += [('Store type', typestr(self._store))]\n if self._chunk_store is not None:\n items += [('Chunk store type', typestr(self._chunk_store))]\n items += [('No. bytes', bytestr(self.nbytes))]\n if self.nbytes_stored > 0:\n items += [\n ('No. bytes stored', bytestr(self.nbytes_stored)),\n ('Storage ratio', '%.1f' % (self.nbytes / self.nbytes_stored)),\n ]\n items += [\n ('Chunks initialized', '%s/%s' % (self.nchunks_initialized, self.nchunks))\n ]\n\n return items\n\n def digest(self, hashname=\"sha1\"):\n \"\"\"\n Compute a checksum for the data. Default uses sha1 for speed.\n\n Examples\n --------\n >>> import binascii\n >>> import zarr\n >>> z = zarr.empty(shape=(10000, 10000), chunks=(1000, 1000))\n >>> binascii.hexlify(z.digest())\n b'041f90bc7a571452af4f850a8ca2c6cddfa8a1ac'\n >>> z = zarr.zeros(shape=(10000, 10000), chunks=(1000, 1000))\n >>> binascii.hexlify(z.digest())\n b'7162d416d26a68063b66ed1f30e0a866e4abed60'\n >>> z = zarr.zeros(shape=(10000, 10000), dtype=\"u1\", chunks=(1000, 1000))\n >>> binascii.hexlify(z.digest())\n b'cb387af37410ae5a3222e893cf3373e4e4f22816'\n \"\"\"\n\n h = hashlib.new(hashname)\n\n for i in itertools.product(*[range(s) for s in self.cdata_shape]):\n h.update(self.chunk_store.get(self._chunk_key(i), b\"\"))\n\n h.update(self.store.get(self._key_prefix + array_meta_key, b\"\"))\n\n h.update(self.store.get(self.attrs.key, b\"\"))\n\n checksum = h.digest()\n\n return checksum\n\n def hexdigest(self, hashname=\"sha1\"):\n \"\"\"\n Compute a checksum for the data. Default uses sha1 for speed.\n\n Examples\n --------\n >>> import zarr\n >>> z = zarr.empty(shape=(10000, 10000), chunks=(1000, 1000))\n >>> z.hexdigest()\n '041f90bc7a571452af4f850a8ca2c6cddfa8a1ac'\n >>> z = zarr.zeros(shape=(10000, 10000), chunks=(1000, 1000))\n >>> z.hexdigest()\n '7162d416d26a68063b66ed1f30e0a866e4abed60'\n >>> z = zarr.zeros(shape=(10000, 10000), dtype=\"u1\", chunks=(1000, 1000))\n >>> z.hexdigest()\n 'cb387af37410ae5a3222e893cf3373e4e4f22816'\n \"\"\"\n\n checksum = binascii.hexlify(self.digest(hashname=hashname))\n\n # This is a bytes object on Python 3 and we want a str.\n if type(checksum) is not str:\n checksum = checksum.decode('utf8')\n\n return checksum\n\n def __getstate__(self):\n return (self._store, self._path, self._read_only, self._chunk_store,\n self._synchronizer, self._cache_metadata, self._attrs.cache)\n\n def __setstate__(self, state):\n self.__init__(*state)\n\n def _synchronized_op(self, f, *args, **kwargs):\n\n if self._synchronizer is None:\n # no synchronization\n lock = nolock\n\n else:\n # synchronize on the array\n mkey = self._key_prefix + array_meta_key\n lock = self._synchronizer[mkey]\n\n with lock:\n self._refresh_metadata_nosync()\n result = f(*args, **kwargs)\n\n return result\n\n def _write_op(self, f, *args, **kwargs):\n\n # guard condition\n if self._read_only:\n err_read_only()\n\n return self._synchronized_op(f, *args, **kwargs)\n\n def resize(self, *args):\n \"\"\"Change the shape of the array by growing or shrinking one or more\n dimensions.\n\n Examples\n --------\n >>> import zarr\n >>> z = zarr.zeros(shape=(10000, 10000), chunks=(1000, 1000))\n >>> z.shape\n (10000, 10000)\n >>> z.resize(20000, 10000)\n >>> z.shape\n (20000, 10000)\n >>> z.resize(30000, 1000)\n >>> z.shape\n (30000, 1000)\n\n Notes\n -----\n When resizing an array, the data are not rearranged in any way.\n\n If one or more dimensions are shrunk, any chunks falling outside the\n new array shape will be deleted from the underlying store.\n\n \"\"\"\n\n return self._write_op(self._resize_nosync, *args)\n\n def _resize_nosync(self, *args):\n\n # normalize new shape argument\n old_shape = self._shape\n new_shape = normalize_resize_args(old_shape, *args)\n old_cdata_shape = self._cdata_shape\n\n # update metadata\n self._shape = new_shape\n self._flush_metadata_nosync()\n\n # determine the new number and arrangement of chunks\n chunks = self._chunks\n new_cdata_shape = tuple(int(np.ceil(s / c))\n for s, c in zip(new_shape, chunks))\n\n # remove any chunks not within range\n chunk_store = self.chunk_store\n for cidx in itertools.product(*[range(n) for n in old_cdata_shape]):\n if all(i < c for i, c in zip(cidx, new_cdata_shape)):\n pass # keep the chunk\n else:\n key = self._chunk_key(cidx)\n try:\n del chunk_store[key]\n except KeyError:\n # chunk not initialized\n pass\n\n def append(self, data, axis=0):\n \"\"\"Append `data` to `axis`.\n\n Parameters\n ----------\n data : array_like\n Data to be appended.\n axis : int\n Axis along which to append.\n\n Returns\n -------\n new_shape : tuple\n\n Notes\n -----\n The size of all dimensions other than `axis` must match between this\n array and `data`.\n\n Examples\n --------\n >>> import numpy as np\n >>> import zarr\n >>> a = np.arange(10000000, dtype='i4').reshape(10000, 1000)\n >>> z = zarr.array(a, chunks=(1000, 100))\n >>> z.shape\n (10000, 1000)\n >>> z.append(a)\n (20000, 1000)\n >>> z.append(np.vstack([a, a]), axis=1)\n (20000, 2000)\n >>> z.shape\n (20000, 2000)\n\n \"\"\"\n return self._write_op(self._append_nosync, data, axis=axis)\n\n def _append_nosync(self, data, axis=0):\n\n # ensure data is array-like\n if not hasattr(data, 'shape'):\n data = np.asanyarray(data)\n\n # ensure shapes are compatible for non-append dimensions\n self_shape_preserved = tuple(s for i, s in enumerate(self._shape)\n if i != axis)\n data_shape_preserved = tuple(s for i, s in enumerate(data.shape)\n if i != axis)\n if self_shape_preserved != data_shape_preserved:\n raise ValueError('shape of data to append is not compatible with the array; '\n 'all dimensions must match except for the dimension being '\n 'appended')\n\n # remember old shape\n old_shape = self._shape\n\n # determine new shape\n new_shape = tuple(\n self._shape[i] if i != axis else self._shape[i] + data.shape[i]\n for i in range(len(self._shape))\n )\n\n # resize\n self._resize_nosync(new_shape)\n\n # store data\n # noinspection PyTypeChecker\n append_selection = tuple(\n slice(None) if i != axis else slice(old_shape[i], new_shape[i])\n for i in range(len(self._shape))\n )\n self[append_selection] = data\n\n return new_shape\n\n def view(self, shape=None, chunks=None, dtype=None,\n fill_value=None, filters=None, read_only=None,\n synchronizer=None):\n \"\"\"Return an array sharing the same data.\n\n Parameters\n ----------\n shape : int or tuple of ints\n Array shape.\n chunks : int or tuple of ints, optional\n Chunk shape.\n dtype : string or dtype, optional\n NumPy dtype.\n fill_value : object\n Default value to use for uninitialized portions of the array.\n filters : sequence, optional\n Sequence of filters to use to encode chunk data prior to\n compression.\n read_only : bool, optional\n True if array should be protected against modification.\n synchronizer : object, optional\n Array synchronizer.\n\n Notes\n -----\n WARNING: This is an experimental feature and should be used with care.\n There are plenty of ways to generate errors and/or cause data\n corruption.\n\n Examples\n --------\n\n Bypass filters:\n\n >>> import zarr\n >>> import numpy as np\n >>> np.random.seed(42)\n >>> labels = ['female', 'male']\n >>> data = np.random.choice(labels, size=10000)\n >>> filters = [zarr.Categorize(labels=labels,\n ... dtype=data.dtype,\n ... astype='u1')]\n >>> a = zarr.array(data, chunks=1000, filters=filters)\n >>> a[:]\n array(['female', 'male', 'female', ..., 'male', 'male', 'female'],\n dtype='<U6')\n >>> v = a.view(dtype='u1', filters=[])\n >>> v.is_view\n True\n >>> v[:]\n array([1, 2, 1, ..., 2, 2, 1], dtype=uint8)\n\n Views can be used to modify data:\n\n >>> x = v[:]\n >>> x.sort()\n >>> v[:] = x\n >>> v[:]\n array([1, 1, 1, ..., 2, 2, 2], dtype=uint8)\n >>> a[:]\n array(['female', 'female', 'female', ..., 'male', 'male', 'male'],\n dtype='<U6')\n\n View as a different dtype with the same item size:\n\n >>> data = np.random.randint(0, 2, size=10000, dtype='u1')\n >>> a = zarr.array(data, chunks=1000)\n >>> a[:]\n array([0, 0, 1, ..., 1, 0, 0], dtype=uint8)\n >>> v = a.view(dtype=bool)\n >>> v[:]\n array([False, False, True, ..., True, False, False], dtype=bool)\n >>> np.all(a[:].view(dtype=bool) == v[:])\n True\n\n An array can be viewed with a dtype with a different item size, however\n some care is needed to adjust the shape and chunk shape so that chunk\n data is interpreted correctly:\n\n >>> data = np.arange(10000, dtype='u2')\n >>> a = zarr.array(data, chunks=1000)\n >>> a[:10]\n array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=uint16)\n >>> v = a.view(dtype='u1', shape=20000, chunks=2000)\n >>> v[:10]\n array([0, 0, 1, 0, 2, 0, 3, 0, 4, 0], dtype=uint8)\n >>> np.all(a[:].view('u1') == v[:])\n True\n\n Change fill value for uninitialized chunks:\n\n >>> a = zarr.full(10000, chunks=1000, fill_value=-1, dtype='i1')\n >>> a[:]\n array([-1, -1, -1, ..., -1, -1, -1], dtype=int8)\n >>> v = a.view(fill_value=42)\n >>> v[:]\n array([42, 42, 42, ..., 42, 42, 42], dtype=int8)\n\n Note that resizing or appending to views is not permitted:\n\n >>> a = zarr.empty(10000)\n >>> v = a.view()\n >>> try:\n ... v.resize(20000)\n ... except PermissionError as e:\n ... print(e)\n operation not permitted for views\n\n \"\"\"\n\n store = self._store\n chunk_store = self._chunk_store\n path = self._path\n if read_only is None:\n read_only = self._read_only\n if synchronizer is None:\n synchronizer = self._synchronizer\n a = Array(store=store, path=path, chunk_store=chunk_store, read_only=read_only,\n synchronizer=synchronizer, cache_metadata=True)\n a._is_view = True\n\n # allow override of some properties\n if dtype is None:\n dtype = self._dtype\n else:\n dtype = np.dtype(dtype)\n a._dtype = dtype\n if shape is None:\n shape = self._shape\n else:\n shape = normalize_shape(shape)\n a._shape = shape\n if chunks is not None:\n chunks = normalize_chunks(chunks, shape, dtype.itemsize)\n a._chunks = chunks\n if fill_value is not None:\n a._fill_value = fill_value\n if filters is not None:\n a._filters = filters\n\n return a\n\n def astype(self, dtype):\n \"\"\"Returns a view that does on the fly type conversion of the underlying data.\n\n Parameters\n ----------\n dtype : string or dtype\n NumPy dtype.\n\n Notes\n -----\n This method returns a new Array object which is a view on the same\n underlying chunk data. Modifying any data via the view is currently\n not permitted and will result in an error. This is an experimental\n feature and its behavior is subject to change in the future.\n\n See Also\n --------\n Array.view\n\n Examples\n --------\n\n >>> import zarr\n >>> import numpy as np\n >>> data = np.arange(100, dtype=np.uint8)\n >>> a = zarr.array(data, chunks=10)\n >>> a[:]\n array([ 0, 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, 31,\n 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,\n 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,\n 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,\n 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,\n 96, 97, 98, 99], dtype=uint8)\n >>> v = a.astype(np.float32)\n >>> v.is_view\n True\n >>> v[:]\n array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,\n 10., 11., 12., 13., 14., 15., 16., 17., 18., 19.,\n 20., 21., 22., 23., 24., 25., 26., 27., 28., 29.,\n 30., 31., 32., 33., 34., 35., 36., 37., 38., 39.,\n 40., 41., 42., 43., 44., 45., 46., 47., 48., 49.,\n 50., 51., 52., 53., 54., 55., 56., 57., 58., 59.,\n 60., 61., 62., 63., 64., 65., 66., 67., 68., 69.,\n 70., 71., 72., 73., 74., 75., 76., 77., 78., 79.,\n 80., 81., 82., 83., 84., 85., 86., 87., 88., 89.,\n 90., 91., 92., 93., 94., 95., 96., 97., 98., 99.],\n dtype=float32)\n \"\"\"\n\n dtype = np.dtype(dtype)\n\n filters = []\n if self._filters:\n filters.extend(self._filters)\n filters.insert(0, AsType(encode_dtype=self._dtype, decode_dtype=dtype))\n\n return self.view(filters=filters, dtype=dtype, read_only=True)\n" ]
[ [ "numpy.array", "numpy.ceil", "numpy.empty", "numpy.copyto", "numpy.zeros", "numpy.ascontiguousarray", "numpy.asfortranarray", "numpy.frombuffer", "numpy.squeeze", "numpy.asanyarray", "numpy.dtype" ] ]
cortwave/camera-model-identification
[ "b2cbac93308bd6e1bc9d38391f5e97f48da99263" ]
[ "arsenyinfo/src/rebalance.py" ]
[ "from glob import glob\n\nimport numpy as np\nimport pandas as pd\nfrom fire import Fire\n\n\ndef main(model_name):\n files = [pd.read_csv(x) for x in glob(f'result/probas_{model_name}*.csv')]\n df = pd.concat(files)\n df = df.groupby('fname').agg(np.sum).reset_index()\n df.to_csv(f'result/blended_probas_{model_name}.csv', index=False)\n df.describe()\n\n classes = ['HTC-1-M7', 'LG-Nexus-5x', 'Motorola-Droid-Maxx', 'Motorola-Nexus-6',\n 'Motorola-X', 'Samsung-Galaxy-Note3', 'Samsung-Galaxy-S4', 'Sony-NEX-7',\n 'iPhone-4s', 'iPhone-6']\n\n df['camera'] = 'tmp'\n\n ix = df.fname.str.contains('manip').index\n while np.any(df.iloc[ix]['camera'] == 'tmp'):\n for c in classes:\n idx = df[df.iloc[ix].camera == 'tmp'][c].argmax()\n df.set_value(col='camera', index=idx, value=c)\n\n ix = df.fname.str.contains('unalt').index\n while np.any(df.iloc[ix]['camera'] == 'tmp'):\n for c in classes:\n idx = df[df.iloc[ix].camera == 'tmp'][c].argmax()\n df.set_value(col='camera', index=idx, value=c)\n\n df['camera_predicted'] = df.apply(lambda x: x[classes].argmax(), axis=1)\n df['weird'] = df.camera_predicted == df.camera\n\n with open('result/weird.txt', 'w') as out:\n weird = df[~df.weird]\n for f in weird['fname']:\n out.write(f'{f}\\n')\n\n unbalanced = df[['fname', 'camera_predicted']]\n unbalanced = unbalanced.rename(columns={'camera_predicted': 'camera'})\n unbalanced.to_csv(f'result/unbalanced_{model_name}.csv', index=False)\n\n df = df[['fname', 'camera']]\n df.to_csv(f'result/balanced_{model_name}.csv', index=False)\n\n unalt = df.fname.apply(lambda x: 'unalt' in x)\n manip = df.fname.apply(lambda x: 'manip' in x)\n\n unalt_df = df.copy()\n unalt_df['camera'][manip] = 'tmp'\n\n manip_df = df.copy()\n manip_df['camera'][unalt] = 'tmp'\n\n unalt_df.to_csv(f'result/{model_name}_only_unalt.csv', index=False)\n manip_df.to_csv(f'result/{model_name}_only_manip.csv', index=False)\n\n\nif __name__ == '__main__':\n Fire(main)\n" ]
[ [ "numpy.any", "pandas.read_csv", "pandas.concat" ] ]
PandaWhoCodes/my_ml_journey
[ "5a82e4340cb33d137495638cf134efce65ac7fac" ]
[ "iris/7.py" ]
[ "import matplotlib.pyplot as plt\nimport numpy\nimport numpy as np\nimport math\n\n\"\"\"-------------------------------------------------\n\tName : calCovariance()\n\tInput = 4*n matrix, mean of Iris data\n\tOutput = 4*4 covariance matrix\n\tDescription : calculate covariance for each component\n-------------------------------------------------\"\"\"\n\n\ndef calCovariance(Iris, mean):\n sepal_length = 0\n sepal_width = 0\n petal_length = 0\n petal_width = 0\n\n IrisCovarianceMatrix = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]\n\n # covariance of sepal_length\n for i in range(0, len(Iris)):\n if i % 4 == 0:\n sepal_length = sepal_length + ((Iris[i] - mean[0]) * (Iris[i] - mean[0]))\n elif i % 4 == 1:\n sepal_width = sepal_width + ((Iris[i - 1] - mean[0]) * (Iris[i] - mean[1]))\n elif i % 4 == 2:\n petal_length = petal_length + ((Iris[i - 2] - mean[0]) * (Iris[i] - mean[2]))\n elif i % 4 == 3:\n petal_width = petal_width + ((Iris[i - 3] - mean[0]) * (Iris[i] - mean[3]))\n\n sepal_length = sepal_length / ((len(Iris) / 4) - 1)\n sepal_width = sepal_width / ((len(Iris) / 4) - 1)\n petal_length = petal_length / ((len(Iris) / 4) - 1)\n petal_width = petal_width / ((len(Iris) / 4) - 1)\n\n IrisCovarianceMatrix[0][0] = sepal_length\n IrisCovarianceMatrix[0][1] = sepal_width\n IrisCovarianceMatrix[0][2] = petal_length\n IrisCovarianceMatrix[0][3] = petal_width\n\n sepal_length = 0\n sepal_width = 0\n petal_length = 0\n petal_width = 0\n\n # covariance of sepal_width\n for i in range(0, len(Iris)):\n if i % 4 == 0:\n sepal_length = sepal_length + ((Iris[i + 1] - mean[1]) * (Iris[i] - mean[0]))\n elif i % 4 == 1:\n sepal_width = sepal_width + ((Iris[i] - mean[1]) * (Iris[i] - mean[1]))\n elif i % 4 == 2:\n petal_length = petal_length + ((Iris[i - 1] - mean[1]) * (Iris[i] - mean[2]))\n elif i % 4 == 3:\n petal_width = petal_width + ((Iris[i - 2] - mean[1]) * (Iris[i] - mean[3]))\n\n sepal_length = sepal_length / ((len(Iris) / 4) - 1)\n sepal_width = sepal_width / ((len(Iris) / 4) - 1)\n petal_length = petal_length / ((len(Iris) / 4) - 1)\n petal_width = petal_width / ((len(Iris) / 4) - 1)\n\n IrisCovarianceMatrix[1][0] = sepal_length\n IrisCovarianceMatrix[1][1] = sepal_width\n IrisCovarianceMatrix[1][2] = petal_length\n IrisCovarianceMatrix[1][3] = petal_width\n\n sepal_length = 0\n sepal_width = 0\n petal_length = 0\n petal_width = 0\n\n # covariance of petal_length\n for i in range(0, len(Iris)):\n if i % 4 == 0:\n sepal_length = sepal_length + ((Iris[i + 2] - mean[2]) * (Iris[i] - mean[0]))\n elif i % 4 == 1:\n sepal_width = sepal_width + ((Iris[i + 1] - mean[2]) * (Iris[i] - mean[1]))\n elif i % 4 == 2:\n petal_length = petal_length + ((Iris[i] - mean[2]) * (Iris[i] - mean[2]))\n elif i % 4 == 3:\n petal_width = petal_width + ((Iris[i - 1] - mean[2]) * (Iris[i] - mean[3]))\n\n sepal_length = sepal_length / ((len(Iris) / 4) - 1)\n sepal_width = sepal_width / ((len(Iris) / 4) - 1)\n petal_length = petal_length / ((len(Iris) / 4) - 1)\n petal_width = petal_width / ((len(Iris) / 4) - 1)\n\n IrisCovarianceMatrix[2][0] = sepal_length\n IrisCovarianceMatrix[2][1] = sepal_width\n IrisCovarianceMatrix[2][2] = petal_length\n IrisCovarianceMatrix[2][3] = petal_width\n\n sepal_length = 0\n sepal_width = 0\n petal_length = 0\n petal_width = 0\n\n # covariance of petal_width\n for i in range(0, len(Iris)):\n if i % 4 == 0:\n sepal_length = sepal_length + ((Iris[i + 3] - mean[3]) * (Iris[i] - mean[0]))\n elif i % 4 == 1:\n sepal_width = sepal_width + ((Iris[i + 2] - mean[3]) * (Iris[i] - mean[1]))\n elif i % 4 == 2:\n petal_length = petal_length + ((Iris[i + 1] - mean[3]) * (Iris[i] - mean[2]))\n elif i % 4 == 3:\n petal_width = petal_width + ((Iris[i] - mean[3]) * (Iris[i] - mean[3]))\n\n sepal_length = sepal_length / ((len(Iris) / 4) - 1)\n sepal_width = sepal_width / ((len(Iris) / 4) - 1)\n petal_length = petal_length / ((len(Iris) / 4) - 1)\n petal_width = petal_width / ((len(Iris) / 4) - 1)\n\n IrisCovarianceMatrix[3][0] = sepal_length\n IrisCovarianceMatrix[3][1] = sepal_width\n IrisCovarianceMatrix[3][2] = petal_length\n IrisCovarianceMatrix[3][3] = petal_width\n\n IrisCovarianceMatrix = np.array(IrisCovarianceMatrix)\n\n print(IrisCovarianceMatrix)\n\n return IrisCovarianceMatrix\n\n\n\"\"\"-------------------------------------------------\n\tName : cal_mean()\n\tInput = 4*n matrix\n\tOutput = 1*4\n\tDescription : calculate mean for each component\n-------------------------------------------------\"\"\"\n\n\ndef cal_mean(Iris):\n sepal_length_mean = 0\n sepal_width_mean = 0\n petal_length_mean = 0\n petal_width_mean = 0\n\n Iris_mean = [0, 0, 0, 0]\n\n for i in range(0, len(Iris)):\n if i % 4 == 0:\n sepal_length_mean = sepal_length_mean + Iris[i]\n elif i % 4 == 1:\n sepal_width_mean = sepal_width_mean + Iris[i]\n elif i % 4 == 2:\n petal_length_mean = petal_length_mean + Iris[i]\n elif i % 4 == 3:\n petal_width_mean = petal_width_mean + Iris[i]\n\n sepal_length_mean = sepal_length_mean / (len(Iris) / 4)\n sepal_width_mean = sepal_width_mean / (len(Iris) / 4)\n petal_length_mean = petal_length_mean / (len(Iris) / 4)\n petal_width_mean = petal_width_mean / (len(Iris) / 4)\n\n Iris_mean[0] = sepal_length_mean\n Iris_mean[1] = sepal_width_mean\n Iris_mean[2] = petal_length_mean\n Iris_mean[3] = petal_width_mean\n\n Iris_mean = np.array(Iris_mean)\n\n print(Iris_mean)\n\n return Iris_mean\n\n\n\"\"\"-------------------------------------------------\n\tName : discriminantFunctions()\n\tInput = 2*n matrix, 2*1 mean matrix, 2*2 covarianceMatrix, value of vi0\n\tOutput = value(gi)\n\tDescription : Calculated using discriminantFunctions\n-------------------------------------------------\"\"\"\n\n\ndef discriminantFunctions(IrisTestData, meanMatrix, covarianceMatrix, vi0):\n cal1 = np.dot(np.dot(np.transpose(IrisTestData), -0.5 * np.linalg.inv(covarianceMatrix)), IrisTestData)\n cal2 = np.dot(np.transpose(np.dot(np.linalg.inv(covarianceMatrix), meanMatrix)), IrisTestData)\n\n result = cal1 + cal2 + vi0\n return result\n\n\n\"\"\"-------------------------------------------------\n\tName : calVi0()\n\tInput = 2*1 mean matrix, 2*2 covarianceMatrix\n\tOutput = value of vi0\n\tDescription : Calculate the required value for the discriminantFunction\n-------------------------------------------------\"\"\"\n\n\ndef calVi0(meanMatrix, covarianceMatrix):\n vi0 = -0.5 * np.dot(np.dot(np.transpose(meanMatrix), np.linalg.inv(covarianceMatrix)), meanMatrix) - 0.5 * np.log2(\n numpy.linalg.det(covarianceMatrix))\n\n return vi0\n\n\n\"\"\"-------------------------------------------------\n\tName : plotTheTraingData()\n\tInput = three of Iris (2*n matrix)\n\tDescription : plot the each iris traing data in graph\n-------------------------------------------------\"\"\"\n\n\ndef plotTheTraningData(setosaData, versicolorData, virginicaData):\n setosaPlot = np.zeros([2, 40])\n versicolorPlot = np.zeros([2, 40])\n virginicaPlot = np.zeros([2, 40])\n\n count = 0\n for i in range(0, 160):\n if i % 4 == 0:\n setosaPlot[0][count] = setosaData[i]\n setosaPlot[1][count] = setosaData[i + 1]\n versicolorPlot[0][count] = versicolorData[i]\n versicolorPlot[1][count] = versicolorData[i + 1]\n virginicaPlot[0][count] = virginicaData[i]\n virginicaPlot[1][count] = virginicaData[i + 1]\n count += 1\n\n plt.axis([4, 8.1, 1.5, 5])\n plt.plot(setosaPlot[0], setosaPlot[1], 'bo')\n plt.plot(versicolorPlot[0], versicolorPlot[1], 'b^')\n plt.plot(virginicaPlot[0], virginicaPlot[1], 'bs')\n\n\n\"\"\"-------------------------------------------------\n\tName : plotTheTestData()\n\tInput = three of Iris (2*n matrix)\n\tDescription : plot the each iris test data in graph\n-------------------------------------------------\"\"\"\n\n\ndef plotTheTestData(setosaData, versicolorData, virginicaData):\n setosaPlot = np.zeros([2, 10])\n versicolorPlot = np.zeros([2, 10])\n virginicaPlot = np.zeros([2, 10])\n\n count = 0\n for i in range(0, 40):\n if i % 4 == 0:\n setosaPlot[0][count] = setosaData[count][0]\n setosaPlot[1][count] = setosaData[count][1]\n versicolorPlot[0][count] = versicolorData[count][0]\n versicolorPlot[1][count] = versicolorData[count][1]\n virginicaPlot[0][count] = virginicaData[count][0]\n virginicaPlot[1][count] = virginicaData[count][1]\n count += 1\n\n plt.plot(setosaPlot[0], setosaPlot[1], 'ko')\n plt.plot(versicolorPlot[0], versicolorPlot[1], 'k^')\n plt.plot(virginicaPlot[0], virginicaPlot[1], 'ks')\n\n\n\"\"\"-------------------------------------------------\n\tName : plotThedecisionBoundaries()\n\tInput = three of Iris g value\n\tDescription : plot the each decision boundary in graph\n-------------------------------------------------\"\"\"\n\n\ndef plotThedecisionBoundaries(g1, g2, g3):\n xx, yy = np.meshgrid(np.arange(4, 8.1, 0.05), np.arange(1, 6, 0.05))\n\n plt.contour(xx, yy, g1 - g2, [0], colors='b')\n plt.contour(xx, yy, g2 - g3, [0], colors='g')\n plt.contour(xx, yy, g3 - g1, [0], colors='r')\n\n\n\"\"\"-------------------------------------------------\n\tName : calMahalanobisDistance()\n\tInput = 2*n matrix, 2*1 mean matrix, 2*2 covariance matrix\n\tOutput = expression of Z\n\tDescription : calculate and plot the each mahalanobis distance in graph\n-------------------------------------------------\"\"\"\n\n\ndef calMahalanobisDistance(Iris, meanVector, covarianceMatrix):\n irisMBPlot = np.zeros([2, 40])\n\n count = 0\n for i in range(0, 160):\n if i % 4 == 0:\n irisMBPlot[0][count] = Iris[i]\n irisMBPlot[1][count] = Iris[i + 1]\n count += 1\n\n xx, yy = np.meshgrid(np.arange(4, 8.1, 0.05), np.arange(1, 6, 0.05))\n\n matrix = np.linalg.inv(covarianceMatrix)\n\n temp1 = (meanVector[0] - xx) * (matrix[0][0]) + (meanVector[1] - yy) * (matrix[1][0])\n temp2 = (meanVector[0] - xx) * (matrix[0][1]) + (meanVector[1] - yy) * (matrix[1][1])\n\n Z = np.sqrt(temp1 * (meanVector[0] - xx) + temp2 * (meanVector[1] - yy)) - 2\n plt.contour(xx, yy, Z, [0], colors='y')\n\n return Z\n\n\n\"\"\"-------------------------------------------------\n\tName : calGListofMD()\n\tInput = 2*n matrix, 2*1 mean matrix, 2*2 covariance matrix\n\tOutput = g value list of each class \n\tDescription : Generate list to determine test data\n-------------------------------------------------\"\"\"\n\n\ndef calGListofMD(Iris, meanVector, covarianceMatrix):\n gList = np.zeros((1, 10))\n matrix = np.linalg.inv(covarianceMatrix)\n\n for i in range(0, len(Iris)):\n temp1 = (meanVector[0] - Iris[i][0]) * (matrix[0][0]) + (meanVector[1] - Iris[i][1]) * (matrix[1][0])\n temp2 = (meanVector[0] - Iris[i][0]) * (matrix[0][1]) + (meanVector[1] - Iris[i][1]) * (matrix[1][1])\n\n Z = np.sqrt(temp1 * (meanVector[0] - Iris[i][0]) + temp2 * (meanVector[1] - Iris[i][1])) - 2\n gList[0][i] = Z\n\n return gList\n\n\n\"\"\"-------------------------------------------------\n\tName : plotClassifyTestData()\n\tInput = 2*n matrix of each class, g value list of eace class, state num\n\tOutput = 3*3 confusion matrix\n\tDescription : Use the boundary to display data in the correct area\n\t\t\t\t\tand calculate confusion matrix\n-------------------------------------------------\"\"\"\n\n\ndef plotClassifyTestData(Iris1, Iris2, Iris3, gList1, gList2, gList3, num):\n cf1, cf2, cf3 = 0, 0, 0\n matrix = np.zeros(3)\n for i in range(0, 10):\n if num == 0:\n if gList1[0][i] - gList1[1][i] > 0:\n cf2 += 1\n plt.plot(Iris1[i][0], Iris1[i][1], 'ro')\n elif gList1[0][i] - gList1[2][i] > 0:\n cf3 += 1\n plt.plot(Iris1[i][0], Iris1[i][1], 'ro')\n else:\n cf1 += 1\n elif num == 1:\n if gList2[1][i] - gList2[0][i] > 0:\n cf1 += 1\n plt.plot(Iris2[i][0], Iris2[i][1], 'r^')\n elif gList2[1][i] - gList2[2][i] > 0:\n cf3 += 1\n plt.plot(Iris2[i][0], Iris2[i][1], 'r^')\n else:\n cf2 += 1\n elif num == 2:\n if gList3[2][i] - gList3[0][i] > 0:\n cf1 += 1\n plt.plot(Iris3[i][0], Iris3[i][1], 'rs')\n elif gList3[2][i] - gList3[1][i] > 0:\n cf2 += 1\n plt.plot(Iris3[i][0], Iris3[i][1], 'rs')\n else:\n cf3 += 1\n\n matrix[0], matrix[1], matrix[2] = cf1, cf2, cf3\n return matrix\n\n\n# -------read file, init variables, calculate confusion matrix\nif __name__ == \"__main__\":\n File = open(\"iris_data_tb.txt\", 'r')\n lines = File.readlines()\n features = []\n\n # variable of Iris Info \n setosa = []\n versicolor = []\n virginica = []\n\n # mean of Iris Info\n setosaMeanVector = []\n versicolorMeanVector = []\n virginicaMeanVector = []\n\n # covariance matrix of Iris Info\n setosaCovarianceMatrix = []\n versicolorCovarianceMatrix = []\n virginicaCovarianceMatrix = []\n\n for line in lines:\n word = line.split(\"\\t\")\n features.append(word)\n\n File.close()\n\n for i in range(0, len(features)):\n if features[i][1] == \"0\" or features[i][1] == \"0\\n\":\n for j in range(0, 4):\n setosa.append(float(features[i][j]))\n elif features[i][1] == \"1\" or features[i][1] == \"1\\n\":\n for j in range(0, 4):\n versicolor.append(float(features[i][j]))\n elif features[i][1] == \"2\" or features[i][1] == \"2\\n\":\n for j in range(0, 4):\n virginica.append(float(features[i][j]))\n\n print(\"----------------- project #1-1 -----------------\")\n print(\"----setosa Mean----\")\n setosaMeanVector = cal_mean(setosa)\n print(\"----versicolor Mean----\")\n versicolorMeanVector = cal_mean(versicolor)\n print(\"----virginica Mean----\")\n virginicaMeanVector = cal_mean(virginica)\n\n print(\"----setosa Covariance Matrix----\")\n setosaCovarianceMatrix = calCovariance(setosa, setosaMeanVector)\n print(\"----versicolor Covariance Matrix----\")\n versicolorCovarianceMatrix = calCovariance(versicolor, versicolorMeanVector)\n print(\"----virginica Covariance Matrix----\")\n virginicaCovarianceMatrix = calCovariance(virginica, virginicaMeanVector)\n\n # --------------------Iris_test.dat.txt read------------------\n File = open(\"iris_data_tb.txt\", 'r')\n lines = File.readlines()\n\n # each value of test data set\n setosaTestData = np.zeros((10, 4))\n versicolorTestData = np.zeros((10, 4))\n virginicaTestData = np.zeros((10, 4))\n\n featuresTestData = []\n\n confusionMatrix = np.zeros((3, 3))\n\n for line in lines:\n word = line.split(\"\\t\")\n featuresTestData.append(word)\n\n File.close()\n\n # save \n for i in range(0, len(featuresTestData)):\n if featuresTestData[i][1] == \"0\" or featuresTestData[i][1] == \"0\\r\\n\":\n for j in range(0, 4):\n setosaTestData[i][j] = (float(featuresTestData[i][j]))\n elif featuresTestData[i][1] == \"1\" or featuresTestData[i][1] == \"1\\r\\n\":\n for j in range(0, 4):\n versicolorTestData[i - 10][j] = (float(featuresTestData[i][j]))\n elif featuresTestData[i][1] == \"2\" or featuresTestData[i][1] == \"2\\r\\n\":\n for j in range(0, 4):\n virginicaTestData[i - 20][j] = (float(featuresTestData[i][j]))\n\n # calculate vi0\n setosaVi0 = calVi0(setosaMeanVector, setosaCovarianceMatrix)\n versicolorVi0 = calVi0(versicolorMeanVector, versicolorCovarianceMatrix)\n virginicaVi0 = calVi0(virginicaMeanVector, virginicaCovarianceMatrix)\n\n # calculate confusion matrix\n for i in range(0, len(setosaTestData)):\n gx1 = discriminantFunctions(setosaTestData[i], setosaMeanVector, setosaCovarianceMatrix, setosaVi0)\n gx2 = discriminantFunctions(setosaTestData[i], versicolorMeanVector, versicolorCovarianceMatrix, versicolorVi0)\n gx3 = discriminantFunctions(setosaTestData[i], virginicaMeanVector, virginicaCovarianceMatrix, virginicaVi0)\n\n if gx1 - gx2 < 0:\n confusionMatrix[0][1] += 1\n elif gx1 - gx3 < 0:\n confusionMatrix[0][2] += 1\n else:\n confusionMatrix[0][0] += 1\n\n for i in range(0, len(versicolorTestData)):\n gx1 = discriminantFunctions(versicolorTestData[i], setosaMeanVector, setosaCovarianceMatrix, setosaVi0)\n gx2 = discriminantFunctions(versicolorTestData[i], versicolorMeanVector, versicolorCovarianceMatrix,\n versicolorVi0)\n gx3 = discriminantFunctions(versicolorTestData[i], virginicaMeanVector, virginicaCovarianceMatrix, virginicaVi0)\n\n if gx2 - gx1 < 0:\n confusionMatrix[1][0] += 1\n elif gx2 - gx3 < 0:\n confusionMatrix[1][2] += 1\n else:\n confusionMatrix[1][1] += 1\n\n for i in range(0, len(virginicaTestData)):\n gx1 = discriminantFunctions(virginicaTestData[i], setosaMeanVector, setosaCovarianceMatrix, setosaVi0)\n gx2 = discriminantFunctions(virginicaTestData[i], versicolorMeanVector, versicolorCovarianceMatrix,\n versicolorVi0)\n gx3 = discriminantFunctions(virginicaTestData[i], virginicaMeanVector, virginicaCovarianceMatrix, virginicaVi0)\n\n if gx3 - gx1 < 0:\n confusionMatrix[2][0] += 1\n elif gx3 - gx2 < 0:\n confusionMatrix[2][1] += 1\n else:\n confusionMatrix[2][2] += 1\n\n print(\"----confusion Matrix----\")\n print(confusionMatrix)\n\n print(\"----------------- project #1-2 -----------------\")\n # ---------------------project #1-2---------------------\n setosa2fMeanVector = setosaMeanVector[0:2]\n versicolor2fMeanVector = versicolorMeanVector[0:2]\n virginica2fMeanVector = virginicaMeanVector[0:2]\n\n setosa2fCovariance = np.zeros((2, 2))\n versicolor2fCovariance = np.zeros((2, 2))\n virginica2fCovariance = np.zeros((2, 2))\n\n setosa2fTestData = np.zeros((10, 2))\n versicolor2fTestData = np.zeros((10, 2))\n virginica2fTestData = np.zeros((10, 2))\n\n for i in range(0, 10):\n setosa2fTestData[i][0] = setosaTestData[i][0]\n setosa2fTestData[i][1] = setosaTestData[i][1]\n versicolor2fTestData[i][0] = versicolorTestData[i][0]\n versicolor2fTestData[i][1] = versicolorTestData[i][1]\n virginica2fTestData[i][0] = virginicaTestData[i][0]\n virginica2fTestData[i][1] = virginicaTestData[i][1]\n\n for i in range(0, 2):\n setosa2fCovariance[i][0] = setosaCovarianceMatrix[i][0]\n setosa2fCovariance[i][1] = setosaCovarianceMatrix[i][1]\n versicolor2fCovariance[i][0] = versicolorCovarianceMatrix[i][0]\n versicolor2fCovariance[i][1] = versicolorCovarianceMatrix[i][1]\n virginica2fCovariance[i][0] = virginicaCovarianceMatrix[i][0]\n virginica2fCovariance[i][1] = virginicaCovarianceMatrix[i][1]\n\n plotTheTraningData(setosa, versicolor, virginica)\n plotTheTestData(setosaTestData, versicolorTestData, virginicaTestData)\n\n print(\"----mean of setosa 2features----\")\n print(setosa2fMeanVector)\n\n print(\"----mean of versicolor 2features----\")\n print(versicolor2fMeanVector)\n\n print(\"----mean of virginica 2features----\")\n print(virginica2fMeanVector)\n\n print(\"----covariance setosa of 2fefatures----\")\n print(setosa2fCovariance)\n\n print(\"----covariance versicolor of 2fefatures----\")\n print(versicolor2fCovariance)\n\n print(\"----covariance virginica of 2fefatures----\")\n print(virginica2fCovariance)\n\n g1 = calMahalanobisDistance(setosa, setosa2fMeanVector, setosa2fCovariance)\n g2 = calMahalanobisDistance(versicolor, versicolor2fMeanVector, versicolor2fCovariance)\n g3 = calMahalanobisDistance(virginica, virginica2fMeanVector, virginica2fCovariance)\n\n plotThedecisionBoundaries(g1, g2, g3)\n\n setosa2fGList = np.zeros((3, 10))\n versicolor2fGList = np.zeros((3, 10))\n virginica2fGList = np.zeros((3, 10))\n\n confusionMatrix2f = np.zeros((3, 3))\n\n setosa2fGList[0] = calGListofMD(setosa2fTestData, setosa2fMeanVector, setosa2fCovariance)\n setosa2fGList[1] = calGListofMD(setosa2fTestData, versicolor2fMeanVector, versicolor2fCovariance)\n setosa2fGList[2] = calGListofMD(setosa2fTestData, virginica2fMeanVector, virginica2fCovariance)\n versicolor2fGList[0] = calGListofMD(versicolor2fTestData, setosa2fMeanVector, setosa2fCovariance)\n versicolor2fGList[1] = calGListofMD(versicolor2fTestData, versicolor2fMeanVector, versicolor2fCovariance)\n versicolor2fGList[2] = calGListofMD(versicolor2fTestData, virginica2fMeanVector, virginica2fCovariance)\n virginica2fGList[0] = calGListofMD(virginica2fTestData, setosa2fMeanVector, setosa2fCovariance)\n virginica2fGList[1] = calGListofMD(virginica2fTestData, versicolor2fMeanVector, versicolor2fCovariance)\n virginica2fGList[2] = calGListofMD(virginica2fTestData, virginica2fMeanVector, virginica2fCovariance)\n\n confusionMatrix2f[0] = plotClassifyTestData(setosa2fTestData, versicolor2fTestData, virginica2fTestData,\n setosa2fGList, versicolor2fGList, virginica2fGList, 0)\n confusionMatrix2f[1] = plotClassifyTestData(setosa2fTestData, versicolor2fTestData, virginica2fTestData,\n setosa2fGList, versicolor2fGList, virginica2fGList, 1)\n confusionMatrix2f[2] = plotClassifyTestData(setosa2fTestData, versicolor2fTestData, virginica2fTestData,\n setosa2fGList, versicolor2fGList, virginica2fGList, 2)\n\n print(\"----Confusion Matrix 2f of test data\")\n print(confusionMatrix2f)\n\n plt.show()\n" ]
[ [ "numpy.array", "numpy.zeros", "matplotlib.pyplot.plot", "numpy.linalg.det", "numpy.arange", "numpy.transpose", "numpy.sqrt", "matplotlib.pyplot.show", "matplotlib.pyplot.contour", "numpy.linalg.inv", "matplotlib.pyplot.axis" ] ]
anze-gn/CBLBs
[ "5a62236e4db3f08e4058da76621a185c64fd24ba" ]
[ "robustness/solver_population.py" ]
[ "import math\nimport pickle \nimport numpy as np\nimport matplotlib.pyplot as plt \nimport matplotlib.ticker as ticker\nimport random as rand \nfrom numpy import random \nfrom sklearn import decomposition \nfrom deap import creator, base, tools, algorithms \nfrom sklearn.decomposition import PCA\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn.cluster import KMeans \nimport matplotlib.ticker as ticker \nimport os.path \n\nfrom model_clb_population import model_clb_population, param_references\n\n\n\nimport time \nimport multiprocessing\n\n'''\nRegions consist of cloud of points and principal component that govern the direction of exploration \n''' \nclass Region: \n def __init__(self, points, model, label, depth=1): \n self.points = np.array(points) \n self.model = model \n self.pca = PCA(n_components=self.model.nParams)\n self.components = None\n self.prevComponents = None \n self.cluster = False\n self.terminated = False \n self.iter = 0 \n self.maxIter = 10 \n self.threshold = 0.001 \n self.label = label\n self.maxVarScale = 6 \n self.minVarScale = 3 \n self.varScaleDt = (self.maxVarScale - self.minVarScale)/(float(self.maxIter)) \n self.varScale = self.maxVarScale \n self.depth = depth \n \n def updateVariance(self): \n self.varScale = self.varScale - self.varScaleDt\n\n def updateIter(self):\n self.iter = self.iter + 1\n self.updateVariance() \n \n def fitPCA(self): \n self.prevComponents = self.components \n self.pca.fit(self.points)\n self.components = self.pca.components_\n \n def transform(self, points): \n return self.pca.transform(points) \n \n def inverse_transform(self, points):\n return self.pca.inverse_transform(points) \n \n def converged(self):\n if self.components is None or self.prevComponents is None: \n return False \n return np.linalg.norm(self.components - self.prevComponents) < self.threshold \n \n def explored(self): \n return self.terminated or self.iter > self.maxIter or self.converged() \n \n'''\nThe main class\n'''\n\n#must be global for parallelization \ncreator.create(\"FitnessMax\", base.Fitness, weights=(1.0,)) \ncreator.create(\"Candidate\", list, fitness=creator.FitnessMax) \n \n \n\nclass Solver:\n def __init__(self, model, populationSize=10000, NGEN = 10, nsamples = 1e5, random_candidates = False): \n self.model = model \n self.populationSize = populationSize \n self.NGEN = NGEN \n self.nsamples = int(nsamples) \n self.indpb = 0.75 \n \n #GA operators\n #creator.create(\"FitnessMax\", base.Fitness, weights=(1.0,)) \n #creator.create(\"Candidate\", list, fitness=creator.FitnessMax) \n self.toolbox = base.Toolbox() \n if random_candidates: \n self.toolbox.register(\"candidate\", self.generateRandomCandidate) \n else:\n self.toolbox.register(\"candidate\", self.generateCandidate) \n self.toolbox.register(\"population\", tools.initRepeat, list, self.toolbox.candidate) \n self.toolbox.register(\"mate\", tools.cxTwoPoint)\n self.toolbox.register(\"mutate\", self.mutateCandidate, indpb=self.indpb, mult=0.5) \n self.toolbox.register(\"select\", tools.selTournament, tournsize=int(self.populationSize/10)) \n \n #estimate initial values with GA\n def findNominalValues(self): \n\n tic = time.perf_counter() \n nominalVals = [] \n \n for evalMode in self.model.modes: \n nominalValsMode = []\n \n #initialize new random population\n self.popu = self.toolbox.population(self.populationSize) \n self.toolbox.register(\"evaluate\", evalMode) \n \n \n pool = multiprocessing.Pool()\n self.toolbox.register(\"map\", pool.map) \n \n \n \n for gen in range(self.NGEN): \n print(gen) \n #generate offspprings with crossover and mutations\n offspring = algorithms.varAnd(self.popu, self.toolbox, cxpb=0.5, mutpb=0.75) \n #evaluate individuals\n fits = self.toolbox.map(self.toolbox.evaluate, offspring) \n for fit, ind in zip(fits, offspring): \n if self.model.isViable(ind, fitness=fit) and ind not in nominalValsMode: \n nominalValsMode.append(ind) \n ind.fitness.values = fit \n #roulete wheel selection\n self.popu = self.toolbox.select(offspring, k=len(self.popu)) \n \n pool.close()\n print(\"Number of viable points: \" + str(len(nominalValsMode))) \n nominalVals.extend(nominalValsMode) \n toc = time.perf_counter()\n print(\"Elapsed time: \" + str(toc - tic) + \"s\") \n return nominalVals \n \n #creates an array of random candidates \n def generateRandomCandidate(self): \n candidate = []\n for ind in range(self.model.nParams): \n candidate.append(random.uniform(self.model.parameter_values[self.model.params[ind]][\"min\"], self.model.parameter_values[self.model.params[ind]][\"max\"])) \n return creator.Candidate(candidate) \n \n \n def generateCandidate(self): \n candidate = []\n for ind in range(self.model.nParams): \n #candidate.append(random.uniform(self.model.parameter_values[self.model.params[ind]][\"min\"], self.model.parameter_values[self.model.params[ind]][\"max\"]))\n\n while True:\n r = random.normal(param_references[ind],np.min([\n \tnp.abs(self.model.parameter_values[self.model.params[ind]][\"min\"] - param_references[ind]),\n\t\t\t\t\t\t\t np.abs(self.model.parameter_values[self.model.params[ind]][\"max\"] - param_references[ind])\n ])/3.0)\n if r > 0:\n break\n\n candidate.append(r)\n\n \n return creator.Candidate(candidate)\n \n def checkOutAllBounds(self, candidate):\n for idx, val in enumerate(candidate):\n if self.checkOutOfBounds(candidate, idx): \n return True \n return False \n \n def checkOutOfBounds(self, candidate, idx): \n #if out of bounds return True \n if candidate[idx] < self.model.parameter_values[self.model.params[idx]][\"min\"] or candidate[idx] > self.model.parameter_values[self.model.params[idx]][\"max\"]: \n return True\n return False \n \n #returns a tuple of mutated candidate \n def mutateCandidate(self, candidate, indpb, mult): \n for idx, val in enumerate(candidate): \n rnd = random.uniform(0, 1)\n if rnd >= indpb:\n rnd2 = random.uniform(1 - mult, 1 + mult) \n candidate[idx] = val*rnd2 \n if candidate[idx] < self.model.parameter_values[self.model.params[idx]][\"min\"]: \n candidate[idx] = self.model.parameter_values[self.model.params[idx]][\"min\"] \n if candidate[idx] > self.model.parameter_values[self.model.params[idx]][\"max\"]: \n candidate[idx] = self.model.parameter_values[self.model.params[idx]][\"max\"] \n return candidate, \n \n def getViablePoints(self, points):\n pool = multiprocessing.Pool()\n\n viables = np.array(pool.map(self.model.isViable, points)) \n viable = np.array(points)[viables]\n \"\"\" \n viable = list() \n i = 0\n for point in points: \n i += 1\n if i % 1000 == 0:\n print(i) \n \n #check if point is viable \n if self.model.isViable(point): \n viable.append(point) \n \"\"\"\n pool.close() \n return viable \n \n # gap statistic method\n # returns the optimal number of clusters \n def gapStatistic(self, region, number_ref = 10, max_clusters = 2, plot = False): \n #sample size is equal to the number of samples in gaussian sampling \n sample_size = self.nsamples \n subjects = np.array(region.points) \n gaps = []\n deviations = [] \n references = [] \n clusters_range = range(1, max_clusters + 1) \n \n transformed = region.transform(subjects) \n #get min and max parameter values in pca space \n minP = np.min(transformed, axis=0) \n maxP = np.max(transformed, axis=0) \n \n for gap_clusters in clusters_range:\n print(gap_clusters) \n reference_inertia = [] \n for index in range(number_ref): \n\n #OBB ... orientated bounding box \n #random sampling within the PCA bounding box \n reference = minP + random.rand(sample_size, self.model.nParams)*(maxP - minP)\n reference = region.inverse_transform(reference) \n \n kmeanModel = KMeans(gap_clusters) \n kmeanModel.fit(reference) \n reference_inertia.append(kmeanModel.inertia_) \n \n kmeanModel = KMeans(gap_clusters) \n kmeanModel.fit(subjects) \n log_ref_inertia = np.log(reference_inertia) \n #calculate gap\n gap = np.mean(log_ref_inertia) - np.log(kmeanModel.inertia_) \n sk = math.sqrt(1 + 1.0/number_ref)*np.std(log_ref_inertia) \n gaps.append(gap) \n deviations.append(sk) \n \n # Plot the gaps \n if plot:\n plt.clf() \n ax = plt.gca() \n ax.xaxis.set_major_locator(ticker.MaxNLocator(integer=True)) \n ax.xaxis.set_major_locator(ticker.MultipleLocator(2)) \n lines = plt.errorbar(clusters_range, gaps, ecolor='dodgerblue', yerr=deviations, fmt='-', color='dodgerblue') \n plt.setp(lines[0], linewidth=1.5) \n plt.ylabel('Gaps')\n plt.show() \n \n #return optimal number of clusters\n for k in range(0, max_clusters - 1): \n if gaps[k] >= gaps[k + 1] - deviations[k + 1]: \n print(\"Optimal number of clusters: \" + str(k + 1)) \n return k + 1 \n print(\"Optimal number of clusters: \" + str(max_clusters)) \n return max_clusters\n #returns the viable volume for \n def getViableVolume(self, viableRegions, sample_size = int(1e4)): #1e4 \n volume = 0 \n\n for region in viableRegions: \n regPoints = region.points\n region.fitPCA() \n transformed = region.transform(regPoints) \n \n minP = np.min(transformed, axis=0) \n maxP = np.max(transformed, axis=0) \n \n dP = maxP - minP\n volB = np.prod(dP) \n\n mcRef = minP + random.rand(sample_size, self.model.nParams)*dP \n mcRef = region.inverse_transform(mcRef) \n \n viaPoints = self.getViablePoints(mcRef) \n count = np.ma.size(viaPoints, axis=0) \n \n #volume for region \n ratio = count/sample_size \n volume = volume + ratio*volB \n \n total = self.model.getTotalVolume()\n ratio = volume/total\n\n description = \"Bounding box volume:\" + str(volB) + \"\\n\" \n description += \"Volume:\" + str(volume) + \"\\n\" \n description += \"Total volume:\" + str(total) + \"\\n\" \n description += \"Volume ratio:\" + str(ratio) \n \n return (volume, total, ratio), description \n\n def setBoxColors(self, bp, nRegions, ax, colors = [\"#0E74C8\", \"#15A357\", \"r\", \"k\"]):\n colorLen = len(colors)\n\n for i in range(nRegions): \n col = colors[i % colorLen] \n plt.setp(bp['boxes'][i], color=col, linewidth=1.5) \n plt.setp(bp['caps'][2*i], color=col, linewidth=1.5) \n plt.setp(bp['caps'][2*i + 1], color=col, linewidth=1.5) \n plt.setp(bp['whiskers'][2*i], color=col, linewidth=1.5) \n plt.setp(bp['whiskers'][2*i + 1], color=col, linewidth=1.5) \n plt.setp(bp['fliers'][i], color=col) \n plt.setp(bp['medians'][i], color=col, linewidth=1.5) \n \n def plotParameterVariances(self, viableSets, names=None, units=None): \n #go through all parameters \n params = self.model.params \n figure = plt.figure() \n nRows = math.ceil(len(params)/3) \n for pcount, param in enumerate(params): \n ax1 = plt.subplot(nRows, 3, pcount+1) \n #if names == None:\n # ax1.set_title(str(param) + str(pcount)) \n #else:\n # ax1.set_title(names[pcount]) \n if units != None:\n plt.ylabel(names[pcount] + \" \" + units[pcount]) \n allRegions = [] \n #go through all regions \n numSets = len(viableSets) \n allNames = []\n allBoxes = []\n for count, reg in enumerate(viableSets): \n points = np.array(reg.points) \n data = points[:,pcount] \n allRegions.append(data) \n allNames.append(\"Region \" + str(count + 1)) \n bp = ax1.boxplot(allRegions, positions=list(range(1, numSets + 1)), widths = 0.4) \n self.setBoxColors(bp, numSets, ax1) \n allBoxes = bp['boxes'] \n \n #draw legend \n figure.legend(allBoxes, allNames, 'lower right')\n plt.show() \n \n #Main method \n def run(self, filename, maxDepth=0): \n #filename is a file to which viable sets will be serialized \n\n #estimate the inital viable set \n viablePoints = self.findNominalValues() \n \n if not viablePoints: \n print(\"No viable points found!\") \n return \n \n #dump viable points to file \n pickle.dump(viablePoints, open(filename + \"ViableSet_IterGA.p\", \"wb+\")) \n \n reg = Region(viablePoints, self.model, \"0\") \n reg.fitPCA() \n \n fpca = PCA(n_components=2) \n fpca.fit(reg.points)\n \n viableSets = list() \n viableSets.append(reg) \n converged = False \n iter = 0 \n \n while not converged: \n converged = True \n iter += 1 \n print(\"Iteration: \" + str(iter)) \n for set in viableSets: \n set.updateIter() \n #if set not already explored \n if not set.explored():\n setSize = len(set.points) \n print(\"Label: \" + set.label) \n print(\"Iter: \" + str(set.iter)) \n print(\"Variance scaling factor: \" + str(set.varScale)) \n converged = False \n \n #sample with 0 mean and scaled variance of prinicpal components \n candidateSet = random.multivariate_normal([0]*self.model.nParams, np.diag(set.pca.explained_variance_)*set.varScale, self.nsamples) \n candidateSet = set.inverse_transform(candidateSet) \n \n #check if parameter values are not out of range \n inBounds = list() \n for cand in candidateSet: \n if not self.checkOutAllBounds(cand): \n inBounds.append(cand) \n inBounds = np.array(inBounds) \n candidateSet = inBounds \n\n Y = fpca.transform(candidateSet) \n X = fpca.transform(set.points) \n \n fig = plt.figure(iter) \n plt.clf() \n plt.scatter(Y[:, 0], Y[:, 1], c=\"red\", alpha=0.1, edgecolor='k', rasterized=True) \n plt.scatter(X[:, 0], X[:, 1], c=\"cornflowerblue\", alpha=0.8, edgecolor='k', rasterized=True) \n \n plt.xlabel('PC 1') \n plt.ylabel('PC 2') \n plt.savefig(filename + \"Set\" + set.label + \"Iter\" + str(set.iter) + \".pdf\") \n #identify viable points \n viablePoints = np.array(self.getViablePoints(candidateSet)) \n \n #if viable set is smaller than number of parameters do not accept it\n print(\"Number of viable points: \" + str(len(viablePoints))) \n pickle.dump(candidateSet, open(filename + \"_Region\" + str(set.label) + \"CandidateSet_Iter\" + str(set.iter) + \".p\", \"wb+\")) \n pickle.dump(viablePoints, open(filename + \"_Region\" + str(set.label) + \"ViableSet_Iter\" + str(set.iter) + \".p\", \"wb+\")) \n set.points = viablePoints \n set.fitPCA() \n \n #if set not already terminated, terminate it and cluster \n elif not set.terminated: \n set.terminated = True \n set.cluster = True \n \n #clustering, check for new clusters \n newViableSets = list() \n for set in viableSets: \n if set.cluster and (maxDepth == 0 or set.depth < maxDepth): \n set.cluster = False \n setLabel = set.label \n setDepth = set.depth \n #determine the optimal number of clusters\n print(\"Clustering set\" + set.label) \n k = self.gapStatistic(set) \n if k > 1: \n #cluster and divide sets based on clustering \n #update the list of sets \n converged = False \n labels = KMeans(n_clusters = k).fit_predict(set.points) \n for i in range(k): \n ind = np.where(labels == i)[0] \n points = set.points[ind]\n reg = Region(points, self.model, setLabel + str(i), depth=setDepth+1) \n reg.fitPCA() \n #append new region to new set \n newViableSets.append(reg) \n #end of clustering \n viableSets.extend(newViableSets) \n #end of while loop \n \nif __name__ == '__main__':\n\n \n filename = os.path.join(\"results_optimization_population\", \"\")\n \n #model = BioProc(np.array([\"protein_production\", \"protein_production\", \"protein_production\", \"protein_production\", \"protein_degradation\", \"protein_degradation\", \"Kd\",\"hill\", \"protein_production\", \"protein_degradation\", \"Kd\", \"hill\"]), model_mode=three_bit_processor_ext, parameter_values=param_values, avg_dev=30) \n model = model_clb_population()\n solver = Solver(model) \n solver.run(filename, maxDepth=1) #do not cluster " ]
[ [ "numpy.random.rand", "matplotlib.pyplot.errorbar", "numpy.min", "numpy.mean", "numpy.where", "numpy.max", "numpy.linalg.norm", "matplotlib.ticker.MaxNLocator", "numpy.log", "numpy.prod", "matplotlib.pyplot.gca", "sklearn.decomposition.PCA", "matplotlib.pyplot.subplot", "numpy.array", "matplotlib.ticker.MultipleLocator", "matplotlib.pyplot.figure", "numpy.std", "matplotlib.pyplot.clf", "matplotlib.pyplot.show", "matplotlib.pyplot.setp", "numpy.ma.size", "matplotlib.pyplot.xlabel", "sklearn.cluster.KMeans", "numpy.random.uniform", "matplotlib.pyplot.ylabel", "numpy.abs", "matplotlib.pyplot.scatter", "numpy.diag" ] ]
deklanw/maxent_graph
[ "cc5a34640630147115e2d6bbccf3980e69bf9934" ]
[ "tests/test_models.py" ]
[ "import pytest\nimport numpy as np\n\nfrom maxent_graph import BICM, DECM, BWCM, ECM, BIECM, RCM\nfrom maxent_graph.util import nx_get_A, nx_get_B\n\nmodels = [\n BICM(nx_get_B(\"data/my_senate_116_bipartite.graphml\")),\n BICM(nx_get_B(\"data/opsahl-southernwomen_bipartite.graphml\")),\n DECM(nx_get_A(\"data/residence_hall.graphml\", weight_key=\"weight\")),\n DECM(nx_get_A(\"data/macaques.graphml\", weight_key=\"weight\")),\n BWCM(\n nx_get_B(\n \"data/plant_pol_kato.graphml\",\n weight_key=\"count\",\n bipartite_key=\"pollinator\",\n )\n ),\n BWCM(\n nx_get_B(\n \"data/plant_pol_vazquez_All_sites_pooled.graphml\",\n weight_key=\"count\",\n bipartite_key=\"pollinator\",\n )\n ),\n BIECM(\n nx_get_B(\n \"data/plant_pol_kato.graphml\",\n weight_key=\"count\",\n bipartite_key=\"pollinator\",\n )\n ),\n BIECM(\n nx_get_B(\n \"data/plant_pol_vazquez_All_sites_pooled.graphml\",\n weight_key=\"count\",\n bipartite_key=\"pollinator\",\n )\n ),\n ECM(nx_get_A(\"data/kangaroo.graphml\", weight_key=\"weight\")),\n ECM(nx_get_A(\"data/train_terrorists.graphml\", weight_key=\"weight\")),\n RCM(nx_get_A(\"data/dutch_school_net_1.graphml\")),\n RCM(nx_get_A(\"data/macaques.graphml\")),\n]\n\n\[email protected](\"model\", models)\ndef test_model(model):\n initial_guess = model.get_initial_guess()\n\n nll_loops = model.neg_log_likelihood_loops(initial_guess)\n\n nll = model.neg_log_likelihood(initial_guess)\n\n assert np.allclose(nll_loops, nll)\n\n ens_loops = model.expected_node_sequence_loops(initial_guess)\n\n ens = model.expected_node_sequence(initial_guess)\n\n assert np.allclose(ens_loops, ens)\n\n solution = model.solve(initial_guess)\n\n assert solution is not None\n assert max(solution.relative_error) < 0.001" ]
[ [ "numpy.allclose" ] ]
yufengyuanx/tensorflow
[ "66d5d1fa0c192ca4c9b75cde216866805eb160f2" ]
[ "tensorflow/python/debug/cli/debugger_cli_common_test.py" ]
[ "# Copyright 2016 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 for Building Blocks of the TensorFlow Debugger CLI.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport stat\nimport tempfile\n\nfrom tensorflow.python.debug.cli import debugger_cli_common\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.platform import googletest\n\n\nclass CommandLineExitTest(test_util.TensorFlowTestCase):\n\n def testConstructionWithoutToken(self):\n exit_exc = debugger_cli_common.CommandLineExit()\n\n self.assertTrue(isinstance(exit_exc, Exception))\n\n def testConstructionWithToken(self):\n exit_exc = debugger_cli_common.CommandLineExit(exit_token={\"foo\": \"bar\"})\n\n self.assertTrue(isinstance(exit_exc, Exception))\n self.assertEqual({\"foo\": \"bar\"}, exit_exc.exit_token)\n\n\nclass RichTextLinesTest(test_util.TensorFlowTestCase):\n\n def testRichTextLinesConstructorComplete(self):\n # Test RichTextLines constructor.\n screen_output = debugger_cli_common.RichTextLines(\n [\"Roses are red\", \"Violets are blue\"],\n font_attr_segs={0: [(0, 5, \"red\")],\n 1: [(0, 7, \"blue\")]},\n annotations={0: \"longer wavelength\",\n 1: \"shorter wavelength\"})\n\n self.assertEqual(2, len(screen_output.lines))\n self.assertEqual(2, len(screen_output.font_attr_segs))\n self.assertEqual(1, len(screen_output.font_attr_segs[0]))\n self.assertEqual(1, len(screen_output.font_attr_segs[1]))\n self.assertEqual(2, len(screen_output.annotations))\n\n self.assertEqual(2, screen_output.num_lines())\n\n def testRichTextLinesConstructorWithInvalidType(self):\n with self.assertRaisesRegexp(ValueError, \"Unexpected type in lines\"):\n debugger_cli_common.RichTextLines(123)\n\n def testRichTextLinesConstructorWithString(self):\n # Test constructing a RichTextLines object with a string, instead of a list\n # of strings.\n screen_output = debugger_cli_common.RichTextLines(\n \"Roses are red\",\n font_attr_segs={0: [(0, 5, \"red\")]},\n annotations={0: \"longer wavelength\"})\n\n self.assertEqual(1, len(screen_output.lines))\n self.assertEqual(1, len(screen_output.font_attr_segs))\n self.assertEqual(1, len(screen_output.font_attr_segs[0]))\n self.assertEqual(1, len(screen_output.annotations))\n\n def testRichTextLinesConstructorIncomplete(self):\n # Test RichTextLines constructor, with incomplete keyword arguments.\n screen_output = debugger_cli_common.RichTextLines(\n [\"Roses are red\", \"Violets are blue\"],\n font_attr_segs={0: [(0, 5, \"red\")],\n 1: [(0, 7, \"blue\")]})\n\n self.assertEqual(2, len(screen_output.lines))\n self.assertEqual(2, len(screen_output.font_attr_segs))\n self.assertEqual(1, len(screen_output.font_attr_segs[0]))\n self.assertEqual(1, len(screen_output.font_attr_segs[1]))\n self.assertEqual({}, screen_output.annotations)\n\n def testModifyRichTextLinesObject(self):\n screen_output = debugger_cli_common.RichTextLines(\n [\"Roses are red\", \"Violets are blue\"])\n\n self.assertEqual(2, len(screen_output.lines))\n\n screen_output.lines.append(\"Sugar is sweet\")\n self.assertEqual(3, len(screen_output.lines))\n\n def testMergeRichTextLines(self):\n screen_output_1 = debugger_cli_common.RichTextLines(\n [\"Roses are red\", \"Violets are blue\"],\n font_attr_segs={0: [(0, 5, \"red\")],\n 1: [(0, 7, \"blue\")]},\n annotations={0: \"longer wavelength\",\n 1: \"shorter wavelength\"})\n screen_output_2 = debugger_cli_common.RichTextLines(\n [\"Lilies are white\", \"Sunflowers are yellow\"],\n font_attr_segs={0: [(0, 6, \"white\")],\n 1: [(0, 7, \"yellow\")]},\n annotations={\n \"metadata\": \"foo\",\n 0: \"full spectrum\",\n 1: \"medium wavelength\"\n })\n\n screen_output_1.extend(screen_output_2)\n\n self.assertEqual(4, screen_output_1.num_lines())\n self.assertEqual([\n \"Roses are red\", \"Violets are blue\", \"Lilies are white\",\n \"Sunflowers are yellow\"\n ], screen_output_1.lines)\n self.assertEqual({\n 0: [(0, 5, \"red\")],\n 1: [(0, 7, \"blue\")],\n 2: [(0, 6, \"white\")],\n 3: [(0, 7, \"yellow\")]\n }, screen_output_1.font_attr_segs)\n self.assertEqual({\n 0: [(0, 5, \"red\")],\n 1: [(0, 7, \"blue\")],\n 2: [(0, 6, \"white\")],\n 3: [(0, 7, \"yellow\")]\n }, screen_output_1.font_attr_segs)\n self.assertEqual({\n \"metadata\": \"foo\",\n 0: \"longer wavelength\",\n 1: \"shorter wavelength\",\n 2: \"full spectrum\",\n 3: \"medium wavelength\"\n }, screen_output_1.annotations)\n\n def testMergeRichTextLinesEmptyOther(self):\n screen_output_1 = debugger_cli_common.RichTextLines(\n [\"Roses are red\", \"Violets are blue\"],\n font_attr_segs={0: [(0, 5, \"red\")],\n 1: [(0, 7, \"blue\")]},\n annotations={0: \"longer wavelength\",\n 1: \"shorter wavelength\"})\n screen_output_2 = debugger_cli_common.RichTextLines([])\n\n screen_output_1.extend(screen_output_2)\n\n self.assertEqual(2, screen_output_1.num_lines())\n self.assertEqual([\"Roses are red\", \"Violets are blue\"],\n screen_output_1.lines)\n self.assertEqual({\n 0: [(0, 5, \"red\")],\n 1: [(0, 7, \"blue\")],\n }, screen_output_1.font_attr_segs)\n self.assertEqual({\n 0: [(0, 5, \"red\")],\n 1: [(0, 7, \"blue\")],\n }, screen_output_1.font_attr_segs)\n self.assertEqual({\n 0: \"longer wavelength\",\n 1: \"shorter wavelength\",\n }, screen_output_1.annotations)\n\n def testMergeRichTextLinesEmptySelf(self):\n screen_output_1 = debugger_cli_common.RichTextLines([])\n screen_output_2 = debugger_cli_common.RichTextLines(\n [\"Roses are red\", \"Violets are blue\"],\n font_attr_segs={0: [(0, 5, \"red\")],\n 1: [(0, 7, \"blue\")]},\n annotations={0: \"longer wavelength\",\n 1: \"shorter wavelength\"})\n\n screen_output_1.extend(screen_output_2)\n\n self.assertEqual(2, screen_output_1.num_lines())\n self.assertEqual([\"Roses are red\", \"Violets are blue\"],\n screen_output_1.lines)\n self.assertEqual({\n 0: [(0, 5, \"red\")],\n 1: [(0, 7, \"blue\")],\n }, screen_output_1.font_attr_segs)\n self.assertEqual({\n 0: [(0, 5, \"red\")],\n 1: [(0, 7, \"blue\")],\n }, screen_output_1.font_attr_segs)\n self.assertEqual({\n 0: \"longer wavelength\",\n 1: \"shorter wavelength\",\n }, screen_output_1.annotations)\n\n def testAppendALineWithAttributeSegmentsWorks(self):\n screen_output_1 = debugger_cli_common.RichTextLines(\n [\"Roses are red\"],\n font_attr_segs={0: [(0, 5, \"red\")]},\n annotations={0: \"longer wavelength\"})\n\n screen_output_1.append(\"Violets are blue\", [(0, 7, \"blue\")])\n\n self.assertEqual([\"Roses are red\", \"Violets are blue\"],\n screen_output_1.lines)\n self.assertEqual({\n 0: [(0, 5, \"red\")],\n 1: [(0, 7, \"blue\")],\n }, screen_output_1.font_attr_segs)\n\n def testPrependALineWithAttributeSegmentsWorks(self):\n screen_output_1 = debugger_cli_common.RichTextLines(\n [\"Roses are red\"],\n font_attr_segs={0: [(0, 5, \"red\")]},\n annotations={0: \"longer wavelength\"})\n\n screen_output_1.prepend(\"Violets are blue\", font_attr_segs=[(0, 7, \"blue\")])\n\n self.assertEqual([\"Violets are blue\", \"Roses are red\"],\n screen_output_1.lines)\n self.assertEqual({\n 0: [(0, 7, \"blue\")],\n 1: [(0, 5, \"red\")],\n }, screen_output_1.font_attr_segs)\n\n def testWriteToFileSucceeds(self):\n screen_output = debugger_cli_common.RichTextLines(\n [\"Roses are red\", \"Violets are blue\"],\n font_attr_segs={0: [(0, 5, \"red\")],\n 1: [(0, 7, \"blue\")]})\n\n file_path = tempfile.mktemp()\n screen_output.write_to_file(file_path)\n\n with gfile.Open(file_path, \"r\") as f:\n self.assertEqual(\"Roses are red\\nViolets are blue\\n\", f.read())\n\n # Clean up.\n gfile.Remove(file_path)\n\n def testAttemptToWriteToADirectoryFails(self):\n screen_output = debugger_cli_common.RichTextLines(\n [\"Roses are red\", \"Violets are blue\"],\n font_attr_segs={0: [(0, 5, \"red\")],\n 1: [(0, 7, \"blue\")]})\n\n with self.assertRaises(Exception):\n screen_output.write_to_file(\"/\")\n\n def testAttemptToWriteToFileInNonexistentDirectoryFails(self):\n screen_output = debugger_cli_common.RichTextLines(\n [\"Roses are red\", \"Violets are blue\"],\n font_attr_segs={0: [(0, 5, \"red\")],\n 1: [(0, 7, \"blue\")]})\n\n file_path = os.path.join(tempfile.mkdtemp(), \"foo\", \"bar.txt\")\n with self.assertRaises(Exception):\n screen_output.write_to_file(file_path)\n\n\nclass CommandHandlerRegistryTest(test_util.TensorFlowTestCase):\n\n def setUp(self):\n self._intentional_error_msg = \"Intentionally raised exception\"\n\n def _noop_handler(self, argv, screen_info=None):\n # A handler that does nothing other than returning \"Done.\"\n return debugger_cli_common.RichTextLines([\"Done.\"])\n\n def _handler_raising_exception(self, argv, screen_info=None):\n # A handler that intentionally raises an exception.\n raise RuntimeError(self._intentional_error_msg)\n\n def _handler_returning_wrong_type(self, argv, screen_info=None):\n # A handler that returns a wrong type, instead of the correct type\n # (RichTextLines).\n return \"Hello\"\n\n def _echo_screen_cols(self, argv, screen_info=None):\n # A handler that uses screen_info.\n return debugger_cli_common.RichTextLines(\n [\"cols = %d\" % screen_info[\"cols\"]])\n\n def _exiting_handler(self, argv, screen_info=None):\n \"\"\"A handler that exits with an exit token.\"\"\"\n\n if argv:\n exit_token = argv[0]\n else:\n exit_token = None\n\n raise debugger_cli_common.CommandLineExit(exit_token=exit_token)\n\n def testRegisterEmptyCommandPrefix(self):\n registry = debugger_cli_common.CommandHandlerRegistry()\n\n # Attempt to register an empty-string as a command prefix should trigger\n # an exception.\n with self.assertRaisesRegexp(ValueError, \"Empty command prefix\"):\n registry.register_command_handler(\"\", self._noop_handler, \"\")\n\n def testRegisterAndInvokeHandler(self):\n registry = debugger_cli_common.CommandHandlerRegistry()\n registry.register_command_handler(\"noop\", self._noop_handler, \"\")\n\n self.assertTrue(registry.is_registered(\"noop\"))\n self.assertFalse(registry.is_registered(\"beep\"))\n\n cmd_output = registry.dispatch_command(\"noop\", [])\n self.assertEqual([\"Done.\"], cmd_output.lines)\n\n # Attempt to invoke an unregistered command prefix should trigger an\n # exception.\n with self.assertRaisesRegexp(ValueError, \"No handler is registered\"):\n registry.dispatch_command(\"beep\", [])\n\n # Empty command prefix should trigger an exception.\n with self.assertRaisesRegexp(ValueError, \"Prefix is empty\"):\n registry.dispatch_command(\"\", [])\n\n def testExitingHandler(self):\n \"\"\"Test that exit exception is correctly raised.\"\"\"\n\n registry = debugger_cli_common.CommandHandlerRegistry()\n registry.register_command_handler(\"exit\", self._exiting_handler, \"\")\n\n self.assertTrue(registry.is_registered(\"exit\"))\n\n exit_token = None\n try:\n registry.dispatch_command(\"exit\", [\"foo\"])\n except debugger_cli_common.CommandLineExit as e:\n exit_token = e.exit_token\n\n self.assertEqual(\"foo\", exit_token)\n\n def testInvokeHandlerWithScreenInfo(self):\n registry = debugger_cli_common.CommandHandlerRegistry()\n\n # Register and invoke a command handler that uses screen_info.\n registry.register_command_handler(\"cols\", self._echo_screen_cols, \"\")\n\n cmd_output = registry.dispatch_command(\n \"cols\", [], screen_info={\"cols\": 100})\n self.assertEqual([\"cols = 100\"], cmd_output.lines)\n\n def testRegisterAndInvokeHandlerWithAliases(self):\n registry = debugger_cli_common.CommandHandlerRegistry()\n registry.register_command_handler(\n \"noop\", self._noop_handler, \"\", prefix_aliases=[\"n\", \"NOOP\"])\n\n # is_registered() should work for full prefix and aliases.\n self.assertTrue(registry.is_registered(\"noop\"))\n self.assertTrue(registry.is_registered(\"n\"))\n self.assertTrue(registry.is_registered(\"NOOP\"))\n\n cmd_output = registry.dispatch_command(\"n\", [])\n self.assertEqual([\"Done.\"], cmd_output.lines)\n\n cmd_output = registry.dispatch_command(\"NOOP\", [])\n self.assertEqual([\"Done.\"], cmd_output.lines)\n\n def testHandlerWithWrongReturnType(self):\n registry = debugger_cli_common.CommandHandlerRegistry()\n registry.register_command_handler(\"wrong_return\",\n self._handler_returning_wrong_type, \"\")\n\n # If the command handler fails to return a RichTextLines instance, an error\n # should be triggered.\n with self.assertRaisesRegexp(\n ValueError,\n \"Return value from command handler.*is not None or a RichTextLines \"\n \"instance\"):\n registry.dispatch_command(\"wrong_return\", [])\n\n def testRegisterDuplicateHandlers(self):\n registry = debugger_cli_common.CommandHandlerRegistry()\n registry.register_command_handler(\"noop\", self._noop_handler, \"\")\n\n # Registering the same command prefix more than once should trigger an\n # exception.\n with self.assertRaisesRegexp(\n ValueError, \"A handler is already registered for command prefix\"):\n registry.register_command_handler(\"noop\", self._noop_handler, \"\")\n\n cmd_output = registry.dispatch_command(\"noop\", [])\n self.assertEqual([\"Done.\"], cmd_output.lines)\n\n def testRegisterDuplicateAliases(self):\n registry = debugger_cli_common.CommandHandlerRegistry()\n registry.register_command_handler(\n \"noop\", self._noop_handler, \"\", prefix_aliases=[\"n\"])\n\n # Clash with existing alias.\n with self.assertRaisesRegexp(ValueError,\n \"clashes with existing prefixes or aliases\"):\n registry.register_command_handler(\n \"cols\", self._echo_screen_cols, \"\", prefix_aliases=[\"n\"])\n\n # The name clash should have prevent the handler from being registered.\n self.assertFalse(registry.is_registered(\"cols\"))\n\n # Aliases can also clash with command prefixes.\n with self.assertRaisesRegexp(ValueError,\n \"clashes with existing prefixes or aliases\"):\n registry.register_command_handler(\n \"cols\", self._echo_screen_cols, \"\", prefix_aliases=[\"noop\"])\n\n self.assertFalse(registry.is_registered(\"cols\"))\n\n def testDispatchHandlerRaisingException(self):\n registry = debugger_cli_common.CommandHandlerRegistry()\n registry.register_command_handler(\"raise_exception\",\n self._handler_raising_exception, \"\")\n\n # The registry should catch and wrap exceptions that occur during command\n # handling.\n cmd_output = registry.dispatch_command(\"raise_exception\", [])\n # The error output contains a stack trace.\n # So the line count should be >= 2.\n self.assertGreater(len(cmd_output.lines), 2)\n self.assertTrue(cmd_output.lines[0].startswith(\n \"Error occurred during handling of command\"))\n self.assertTrue(cmd_output.lines[1].endswith(self._intentional_error_msg))\n\n def testRegisterNonCallableHandler(self):\n registry = debugger_cli_common.CommandHandlerRegistry()\n\n # Attempt to register a non-callable handler should fail.\n with self.assertRaisesRegexp(ValueError, \"handler is not callable\"):\n registry.register_command_handler(\"non_callable\", 1, \"\")\n\n def testRegisterHandlerWithInvalidHelpInfoType(self):\n registry = debugger_cli_common.CommandHandlerRegistry()\n\n with self.assertRaisesRegexp(ValueError, \"help_info is not a str\"):\n registry.register_command_handler(\"noop\", self._noop_handler, [\"foo\"])\n\n def testGetHelpFull(self):\n registry = debugger_cli_common.CommandHandlerRegistry()\n registry.register_command_handler(\n \"noop\",\n self._noop_handler,\n \"No operation.\\nI.e., do nothing.\",\n prefix_aliases=[\"n\", \"NOOP\"])\n registry.register_command_handler(\n \"cols\",\n self._echo_screen_cols,\n \"Show screen width in number of columns.\",\n prefix_aliases=[\"c\"])\n\n help_lines = registry.get_help().lines\n\n # The help info should list commands in alphabetically sorted order,\n # regardless of order in which the commands are reigstered.\n self.assertEqual(\"cols\", help_lines[0])\n self.assertTrue(help_lines[1].endswith(\"Aliases: c\"))\n self.assertFalse(help_lines[2])\n self.assertTrue(help_lines[3].endswith(\n \"Show screen width in number of columns.\"))\n\n self.assertFalse(help_lines[4])\n self.assertFalse(help_lines[5])\n\n # The default help command should appear in the help output.\n self.assertEqual(\"help\", help_lines[6])\n\n self.assertEqual(\"noop\", help_lines[12])\n self.assertTrue(help_lines[13].endswith(\"Aliases: n, NOOP\"))\n self.assertFalse(help_lines[14])\n self.assertTrue(help_lines[15].endswith(\"No operation.\"))\n self.assertTrue(help_lines[16].endswith(\"I.e., do nothing.\"))\n\n def testGetHelpSingleCommand(self):\n registry = debugger_cli_common.CommandHandlerRegistry()\n registry.register_command_handler(\n \"noop\",\n self._noop_handler,\n \"No operation.\\nI.e., do nothing.\",\n prefix_aliases=[\"n\", \"NOOP\"])\n registry.register_command_handler(\n \"cols\",\n self._echo_screen_cols,\n \"Show screen width in number of columns.\",\n prefix_aliases=[\"c\"])\n\n # Get help info for one of the two commands, using full prefix.\n help_lines = registry.get_help(\"cols\").lines\n\n self.assertTrue(help_lines[0].endswith(\"cols\"))\n self.assertTrue(help_lines[1].endswith(\"Aliases: c\"))\n self.assertFalse(help_lines[2])\n self.assertTrue(help_lines[3].endswith(\n \"Show screen width in number of columns.\"))\n\n # Get help info for one of the two commands, using alias.\n help_lines = registry.get_help(\"c\").lines\n\n self.assertTrue(help_lines[0].endswith(\"cols\"))\n self.assertTrue(help_lines[1].endswith(\"Aliases: c\"))\n self.assertFalse(help_lines[2])\n self.assertTrue(help_lines[3].endswith(\n \"Show screen width in number of columns.\"))\n\n # Get help info for a nonexistent command.\n help_lines = registry.get_help(\"foo\").lines\n\n self.assertEqual(\"Invalid command prefix: \\\"foo\\\"\", help_lines[0])\n\n def testHelpCommandWithoutIntro(self):\n registry = debugger_cli_common.CommandHandlerRegistry()\n registry.register_command_handler(\n \"noop\",\n self._noop_handler,\n \"No operation.\\nI.e., do nothing.\",\n prefix_aliases=[\"n\", \"NOOP\"])\n registry.register_command_handler(\n \"cols\",\n self._echo_screen_cols,\n \"Show screen width in number of columns.\",\n prefix_aliases=[\"c\"])\n\n # Get help for all commands.\n output = registry.dispatch_command(\"help\", [])\n self.assertEqual([\"cols\", \" Aliases: c\", \"\",\n \" Show screen width in number of columns.\", \"\", \"\",\n \"help\", \" Aliases: h\", \"\", \" Print this help message.\",\n \"\", \"\", \"noop\", \" Aliases: n, NOOP\", \"\",\n \" No operation.\", \" I.e., do nothing.\", \"\", \"\"],\n output.lines)\n\n # Get help for one specific command prefix.\n output = registry.dispatch_command(\"help\", [\"noop\"])\n self.assertEqual([\"noop\", \" Aliases: n, NOOP\", \"\", \" No operation.\",\n \" I.e., do nothing.\"], output.lines)\n\n # Get help for a nonexistent command prefix.\n output = registry.dispatch_command(\"help\", [\"foo\"])\n self.assertEqual([\"Invalid command prefix: \\\"foo\\\"\"], output.lines)\n\n def testHelpCommandWithIntro(self):\n registry = debugger_cli_common.CommandHandlerRegistry()\n registry.register_command_handler(\n \"noop\",\n self._noop_handler,\n \"No operation.\\nI.e., do nothing.\",\n prefix_aliases=[\"n\", \"NOOP\"])\n\n help_intro = debugger_cli_common.RichTextLines(\n [\"Introductory comments.\", \"\"])\n registry.set_help_intro(help_intro)\n\n output = registry.dispatch_command(\"help\", [])\n self.assertEqual(help_intro.lines + [\n \"help\", \" Aliases: h\", \"\", \" Print this help message.\", \"\", \"\",\n \"noop\", \" Aliases: n, NOOP\", \"\", \" No operation.\",\n \" I.e., do nothing.\", \"\", \"\"\n ], output.lines)\n\n\nclass RegexFindTest(test_util.TensorFlowTestCase):\n\n def setUp(self):\n self._orig_screen_output = debugger_cli_common.RichTextLines(\n [\"Roses are red\", \"Violets are blue\"])\n\n def testRegexFindWithoutExistingFontAttrSegs(self):\n new_screen_output = debugger_cli_common.regex_find(self._orig_screen_output,\n \"are\", \"yellow\")\n\n self.assertEqual(2, len(new_screen_output.font_attr_segs))\n self.assertEqual([(6, 9, \"yellow\")], new_screen_output.font_attr_segs[0])\n self.assertEqual([(8, 11, \"yellow\")], new_screen_output.font_attr_segs[1])\n\n # Check field in annotations carrying a list of matching line indices.\n self.assertEqual([0, 1], new_screen_output.annotations[\n debugger_cli_common.REGEX_MATCH_LINES_KEY])\n\n def testRegexFindWithExistingFontAttrSegs(self):\n # Add a font attribute segment first.\n self._orig_screen_output.font_attr_segs[0] = [(9, 12, \"red\")]\n self.assertEqual(1, len(self._orig_screen_output.font_attr_segs))\n\n new_screen_output = debugger_cli_common.regex_find(self._orig_screen_output,\n \"are\", \"yellow\")\n self.assertEqual(2, len(new_screen_output.font_attr_segs))\n\n self.assertEqual([(6, 9, \"yellow\"), (9, 12, \"red\")],\n new_screen_output.font_attr_segs[0])\n\n self.assertEqual([0, 1], new_screen_output.annotations[\n debugger_cli_common.REGEX_MATCH_LINES_KEY])\n\n def testRegexFindWithNoMatches(self):\n new_screen_output = debugger_cli_common.regex_find(self._orig_screen_output,\n \"infrared\", \"yellow\")\n\n self.assertEqual({}, new_screen_output.font_attr_segs)\n self.assertEqual([], new_screen_output.annotations[\n debugger_cli_common.REGEX_MATCH_LINES_KEY])\n\n def testInvalidRegex(self):\n with self.assertRaisesRegexp(ValueError, \"Invalid regular expression\"):\n debugger_cli_common.regex_find(self._orig_screen_output, \"[\", \"yellow\")\n\n def testRegexFindOnPrependedLinesWorks(self):\n rich_lines = debugger_cli_common.RichTextLines([\"Violets are blue\"])\n rich_lines.prepend([\"Roses are red\"])\n searched_rich_lines = debugger_cli_common.regex_find(\n rich_lines, \"red\", \"bold\")\n self.assertEqual(\n {0: [(10, 13, \"bold\")]}, searched_rich_lines.font_attr_segs)\n\n rich_lines = debugger_cli_common.RichTextLines([\"Violets are blue\"])\n rich_lines.prepend([\"A poem\"], font_attr_segs=[(0, 1, \"underline\")])\n searched_rich_lines = debugger_cli_common.regex_find(\n rich_lines, \"poem\", \"italic\")\n self.assertEqual(\n {0: [(0, 1, \"underline\"), (2, 6, \"italic\")]},\n searched_rich_lines.font_attr_segs)\n\n\nclass WrapScreenOutputTest(test_util.TensorFlowTestCase):\n\n def setUp(self):\n self._orig_screen_output = debugger_cli_common.RichTextLines(\n [\"Folk song:\", \"Roses are red\", \"Violets are blue\"],\n font_attr_segs={1: [(0, 5, \"red\"), (6, 9, \"gray\"), (10, 12, \"red\"),\n (12, 13, \"crimson\")],\n 2: [(0, 7, \"blue\"), (8, 11, \"gray\"), (12, 14, \"blue\"),\n (14, 16, \"indigo\")]},\n annotations={1: \"longer wavelength\",\n 2: \"shorter wavelength\"})\n\n def testNoActualWrapping(self):\n # Large column limit should lead to no actual wrapping.\n out, new_line_indices = debugger_cli_common.wrap_rich_text_lines(\n self._orig_screen_output, 100)\n\n self.assertEqual(self._orig_screen_output.lines, out.lines)\n self.assertEqual(self._orig_screen_output.font_attr_segs,\n out.font_attr_segs)\n self.assertEqual(self._orig_screen_output.annotations, out.annotations)\n self.assertEqual(new_line_indices, [0, 1, 2])\n\n def testWrappingWithAttrCutoff(self):\n out, new_line_indices = debugger_cli_common.wrap_rich_text_lines(\n self._orig_screen_output, 11)\n\n # Add non-row-index field to out.\n out.annotations[\"metadata\"] = \"foo\"\n\n # Check wrapped text.\n self.assertEqual(5, len(out.lines))\n self.assertEqual(\"Folk song:\", out.lines[0])\n self.assertEqual(\"Roses are r\", out.lines[1])\n self.assertEqual(\"ed\", out.lines[2])\n self.assertEqual(\"Violets are\", out.lines[3])\n self.assertEqual(\" blue\", out.lines[4])\n\n # Check wrapped font_attr_segs.\n self.assertFalse(0 in out.font_attr_segs)\n self.assertEqual([(0, 5, \"red\"), (6, 9, \"gray\"), (10, 11, \"red\")],\n out.font_attr_segs[1])\n self.assertEqual([(0, 1, \"red\"), (1, 2, \"crimson\")], out.font_attr_segs[2])\n self.assertEqual([(0, 7, \"blue\"), (8, 11, \"gray\")], out.font_attr_segs[3])\n self.assertEqual([(1, 3, \"blue\"), (3, 5, \"indigo\")], out.font_attr_segs[4])\n\n # Check annotations.\n self.assertFalse(0 in out.annotations)\n self.assertEqual(\"longer wavelength\", out.annotations[1])\n self.assertFalse(2 in out.annotations)\n self.assertEqual(\"shorter wavelength\", out.annotations[3])\n self.assertFalse(4 in out.annotations)\n\n # Chec that the non-row-index field is present in output.\n self.assertEqual(\"foo\", out.annotations[\"metadata\"])\n\n self.assertEqual(new_line_indices, [0, 1, 3])\n\n def testWrappingWithMultipleAttrCutoff(self):\n self._orig_screen_output = debugger_cli_common.RichTextLines(\n [\"Folk song:\", \"Roses are red\", \"Violets are blue\"],\n font_attr_segs={1: [(0, 12, \"red\")],\n 2: [(1, 16, \"blue\")]},\n annotations={1: \"longer wavelength\",\n 2: \"shorter wavelength\"})\n\n out, new_line_indices = debugger_cli_common.wrap_rich_text_lines(\n self._orig_screen_output, 5)\n\n # Check wrapped text.\n self.assertEqual(9, len(out.lines))\n self.assertEqual(\"Folk \", out.lines[0])\n self.assertEqual(\"song:\", out.lines[1])\n self.assertEqual(\"Roses\", out.lines[2])\n self.assertEqual(\" are \", out.lines[3])\n self.assertEqual(\"red\", out.lines[4])\n self.assertEqual(\"Viole\", out.lines[5])\n self.assertEqual(\"ts ar\", out.lines[6])\n self.assertEqual(\"e blu\", out.lines[7])\n self.assertEqual(\"e\", out.lines[8])\n\n # Check wrapped font_attr_segs.\n self.assertFalse(0 in out.font_attr_segs)\n self.assertFalse(1 in out.font_attr_segs)\n self.assertEqual([(0, 5, \"red\")], out.font_attr_segs[2])\n self.assertEqual([(0, 5, \"red\")], out.font_attr_segs[3])\n self.assertEqual([(0, 2, \"red\")], out.font_attr_segs[4])\n self.assertEqual([(1, 5, \"blue\")], out.font_attr_segs[5])\n self.assertEqual([(0, 5, \"blue\")], out.font_attr_segs[6])\n self.assertEqual([(0, 5, \"blue\")], out.font_attr_segs[7])\n self.assertEqual([(0, 1, \"blue\")], out.font_attr_segs[8])\n\n # Check annotations.\n self.assertFalse(0 in out.annotations)\n self.assertFalse(1 in out.annotations)\n self.assertEqual(\"longer wavelength\", out.annotations[2])\n self.assertFalse(3 in out.annotations)\n self.assertFalse(4 in out.annotations)\n self.assertEqual(\"shorter wavelength\", out.annotations[5])\n self.assertFalse(6 in out.annotations)\n self.assertFalse(7 in out.annotations)\n self.assertFalse(8 in out.annotations)\n\n self.assertEqual(new_line_indices, [0, 2, 5])\n\n def testWrappingInvalidArguments(self):\n with self.assertRaisesRegexp(ValueError,\n \"Invalid type of input screen_output\"):\n debugger_cli_common.wrap_rich_text_lines(\"foo\", 12)\n\n with self.assertRaisesRegexp(ValueError, \"Invalid type of input cols\"):\n debugger_cli_common.wrap_rich_text_lines(\n debugger_cli_common.RichTextLines([\"foo\", \"bar\"]), \"12\")\n\n def testWrappingEmptyInput(self):\n out, new_line_indices = debugger_cli_common.wrap_rich_text_lines(\n debugger_cli_common.RichTextLines([]), 10)\n\n self.assertEqual([], out.lines)\n self.assertEqual([], new_line_indices)\n\n\nclass SliceRichTextLinesTest(test_util.TensorFlowTestCase):\n\n def setUp(self):\n self._original = debugger_cli_common.RichTextLines(\n [\"Roses are red\", \"Violets are blue\"],\n font_attr_segs={0: [(0, 5, \"red\")],\n 1: [(0, 7, \"blue\")]},\n annotations={\n 0: \"longer wavelength\",\n 1: \"shorter wavelength\",\n \"foo_metadata\": \"bar\"\n })\n\n def testSliceBeginning(self):\n sliced = self._original.slice(0, 1)\n\n self.assertEqual([\"Roses are red\"], sliced.lines)\n self.assertEqual({0: [(0, 5, \"red\")]}, sliced.font_attr_segs)\n\n # Non-line-number metadata should be preseved.\n self.assertEqual({\n 0: \"longer wavelength\",\n \"foo_metadata\": \"bar\"\n }, sliced.annotations)\n\n self.assertEqual(1, sliced.num_lines())\n\n def testSliceEnd(self):\n sliced = self._original.slice(1, 2)\n\n self.assertEqual([\"Violets are blue\"], sliced.lines)\n\n # The line index should have changed from 1 to 0.\n self.assertEqual({0: [(0, 7, \"blue\")]}, sliced.font_attr_segs)\n self.assertEqual({\n 0: \"shorter wavelength\",\n \"foo_metadata\": \"bar\"\n }, sliced.annotations)\n\n self.assertEqual(1, sliced.num_lines())\n\n def testAttemptSliceWithNegativeIndex(self):\n with self.assertRaisesRegexp(ValueError, \"Encountered negative index\"):\n self._original.slice(0, -1)\n\n\nclass TabCompletionRegistryTest(test_util.TensorFlowTestCase):\n\n def setUp(self):\n self._tc_reg = debugger_cli_common.TabCompletionRegistry()\n\n # Register the items in an unsorted order deliberately, to test the sorted\n # output from get_completions().\n self._tc_reg.register_tab_comp_context(\n [\"print_tensor\", \"pt\"],\n [\"node_b:1\", \"node_b:2\", \"node_a:1\", \"node_a:2\"])\n self._tc_reg.register_tab_comp_context([\"node_info\"],\n [\"node_c\", \"node_b\", \"node_a\"])\n\n def testTabCompletion(self):\n # The returned completions should have sorted order.\n self.assertEqual(\n ([\"node_a:1\", \"node_a:2\", \"node_b:1\", \"node_b:2\"], \"node_\"),\n self._tc_reg.get_completions(\"print_tensor\", \"node_\"))\n\n self.assertEqual(([\"node_a:1\", \"node_a:2\", \"node_b:1\", \"node_b:2\"],\n \"node_\"), self._tc_reg.get_completions(\"pt\", \"\"))\n\n self.assertEqual(([\"node_a:1\", \"node_a:2\"], \"node_a:\"),\n self._tc_reg.get_completions(\"print_tensor\", \"node_a\"))\n\n self.assertEqual(([\"node_a:1\"], \"node_a:1\"),\n self._tc_reg.get_completions(\"pt\", \"node_a:1\"))\n\n self.assertEqual(([], \"\"),\n self._tc_reg.get_completions(\"print_tensor\", \"node_a:3\"))\n\n self.assertEqual((None, None), self._tc_reg.get_completions(\"foo\", \"node_\"))\n\n def testExtendCompletionItems(self):\n self.assertEqual(\n ([\"node_a:1\", \"node_a:2\", \"node_b:1\", \"node_b:2\"], \"node_\"),\n self._tc_reg.get_completions(\"print_tensor\", \"node_\"))\n self.assertEqual(([\"node_a\", \"node_b\", \"node_c\"], \"node_\"),\n self._tc_reg.get_completions(\"node_info\", \"node_\"))\n\n self._tc_reg.extend_comp_items(\"print_tensor\", [\"node_A:1\", \"node_A:2\"])\n\n self.assertEqual(([\"node_A:1\", \"node_A:2\", \"node_a:1\", \"node_a:2\",\n \"node_b:1\", \"node_b:2\"], \"node_\"),\n self._tc_reg.get_completions(\"print_tensor\", \"node_\"))\n\n # Extending the completions for one of the context's context words should\n # have taken effect on other context words of the same context as well.\n self.assertEqual(([\"node_A:1\", \"node_A:2\", \"node_a:1\", \"node_a:2\",\n \"node_b:1\", \"node_b:2\"], \"node_\"),\n self._tc_reg.get_completions(\"pt\", \"node_\"))\n self.assertEqual(([\"node_a\", \"node_b\", \"node_c\"], \"node_\"),\n self._tc_reg.get_completions(\"node_info\", \"node_\"))\n\n def testExtendCompletionItemsNonexistentContext(self):\n with self.assertRaisesRegexp(\n KeyError, \"Context word \\\"foo\\\" has not been registered\"):\n self._tc_reg.extend_comp_items(\"foo\", [\"node_A:1\", \"node_A:2\"])\n\n def testRemoveCompletionItems(self):\n self.assertEqual(\n ([\"node_a:1\", \"node_a:2\", \"node_b:1\", \"node_b:2\"], \"node_\"),\n self._tc_reg.get_completions(\"print_tensor\", \"node_\"))\n self.assertEqual(([\"node_a\", \"node_b\", \"node_c\"], \"node_\"),\n self._tc_reg.get_completions(\"node_info\", \"node_\"))\n\n self._tc_reg.remove_comp_items(\"pt\", [\"node_a:1\", \"node_a:2\"])\n\n self.assertEqual(([\"node_b:1\", \"node_b:2\"], \"node_b:\"),\n self._tc_reg.get_completions(\"print_tensor\", \"node_\"))\n self.assertEqual(([\"node_a\", \"node_b\", \"node_c\"], \"node_\"),\n self._tc_reg.get_completions(\"node_info\", \"node_\"))\n\n def testRemoveCompletionItemsNonexistentContext(self):\n with self.assertRaisesRegexp(\n KeyError, \"Context word \\\"foo\\\" has not been registered\"):\n self._tc_reg.remove_comp_items(\"foo\", [\"node_a:1\", \"node_a:2\"])\n\n def testDeregisterContext(self):\n self.assertEqual(\n ([\"node_a:1\", \"node_a:2\", \"node_b:1\", \"node_b:2\"], \"node_\"),\n self._tc_reg.get_completions(\"print_tensor\", \"node_\"))\n self.assertEqual(([\"node_a\", \"node_b\", \"node_c\"], \"node_\"),\n self._tc_reg.get_completions(\"node_info\", \"node_\"))\n\n self._tc_reg.deregister_context([\"print_tensor\"])\n\n self.assertEqual((None, None),\n self._tc_reg.get_completions(\"print_tensor\", \"node_\"))\n\n # The alternative context word should be unaffected.\n self.assertEqual(\n ([\"node_a:1\", \"node_a:2\", \"node_b:1\", \"node_b:2\"], \"node_\"),\n self._tc_reg.get_completions(\"pt\", \"node_\"))\n\n def testDeregisterNonexistentContext(self):\n self.assertEqual(\n ([\"node_a:1\", \"node_a:2\", \"node_b:1\", \"node_b:2\"], \"node_\"),\n self._tc_reg.get_completions(\"print_tensor\", \"node_\"))\n self.assertEqual(([\"node_a\", \"node_b\", \"node_c\"], \"node_\"),\n self._tc_reg.get_completions(\"node_info\", \"node_\"))\n\n self._tc_reg.deregister_context([\"print_tensor\"])\n\n with self.assertRaisesRegexp(\n KeyError,\n \"Cannot deregister unregistered context word \\\"print_tensor\\\"\"):\n self._tc_reg.deregister_context([\"print_tensor\"])\n\n\nclass CommandHistoryTest(test_util.TensorFlowTestCase):\n\n def setUp(self):\n self._cmd_hist = debugger_cli_common.CommandHistory(limit=3)\n self._history_file_path = os.path.join(\n os.path.expanduser(\"~\"),\n debugger_cli_common.CommandHistory._HISTORY_FILE_NAME)\n\n def tearDown(self):\n if os.path.isfile(self._history_file_path):\n os.remove(self._history_file_path)\n\n def testLookUpMostRecent(self):\n self.assertEqual([], self._cmd_hist.most_recent_n(3))\n\n self._cmd_hist.add_command(\"list_tensors\")\n self._cmd_hist.add_command(\"node_info node_a\")\n\n self.assertEqual([\"node_info node_a\"], self._cmd_hist.most_recent_n(1))\n self.assertEqual([\"list_tensors\", \"node_info node_a\"],\n self._cmd_hist.most_recent_n(2))\n self.assertEqual([\"list_tensors\", \"node_info node_a\"],\n self._cmd_hist.most_recent_n(3))\n\n self._cmd_hist.add_command(\"node_info node_b\")\n\n self.assertEqual([\"node_info node_b\"], self._cmd_hist.most_recent_n(1))\n self.assertEqual([\"node_info node_a\", \"node_info node_b\"],\n self._cmd_hist.most_recent_n(2))\n self.assertEqual([\"list_tensors\", \"node_info node_a\", \"node_info node_b\"],\n self._cmd_hist.most_recent_n(3))\n self.assertEqual([\"list_tensors\", \"node_info node_a\", \"node_info node_b\"],\n self._cmd_hist.most_recent_n(4))\n\n # Go over the limit.\n self._cmd_hist.add_command(\"node_info node_a\")\n\n self.assertEqual([\"node_info node_a\"], self._cmd_hist.most_recent_n(1))\n self.assertEqual([\"node_info node_b\", \"node_info node_a\"],\n self._cmd_hist.most_recent_n(2))\n self.assertEqual(\n [\"node_info node_a\", \"node_info node_b\", \"node_info node_a\"],\n self._cmd_hist.most_recent_n(3))\n self.assertEqual(\n [\"node_info node_a\", \"node_info node_b\", \"node_info node_a\"],\n self._cmd_hist.most_recent_n(4))\n\n def testLookUpPrefix(self):\n self._cmd_hist.add_command(\"node_info node_b\")\n self._cmd_hist.add_command(\"list_tensors\")\n self._cmd_hist.add_command(\"node_info node_a\")\n\n self.assertEqual([\"node_info node_b\", \"node_info node_a\"],\n self._cmd_hist.lookup_prefix(\"node_info\", 10))\n\n self.assertEqual([\"node_info node_a\"], self._cmd_hist.lookup_prefix(\n \"node_info\", 1))\n\n self.assertEqual([], self._cmd_hist.lookup_prefix(\"print_tensor\", 10))\n\n def testAddNonStrCommand(self):\n with self.assertRaisesRegexp(\n TypeError, \"Attempt to enter non-str entry to command history\"):\n self._cmd_hist.add_command([\"print_tensor node_a:0\"])\n\n def testRepeatingCommandsDoNotGetLoggedRepeatedly(self):\n self._cmd_hist.add_command(\"help\")\n self._cmd_hist.add_command(\"help\")\n\n self.assertEqual([\"help\"], self._cmd_hist.most_recent_n(2))\n\n def testCommandHistoryFileIsCreated(self):\n self.assertFalse(os.path.isfile(self._history_file_path))\n self._cmd_hist.add_command(\"help\")\n self.assertTrue(os.path.isfile(self._history_file_path))\n with open(self._history_file_path, \"rt\") as f:\n self.assertEqual([\"help\\n\"], f.readlines())\n\n def testLoadingCommandHistoryFileObeysLimit(self):\n self._cmd_hist.add_command(\"help 1\")\n self._cmd_hist.add_command(\"help 2\")\n self._cmd_hist.add_command(\"help 3\")\n self._cmd_hist.add_command(\"help 4\")\n\n cmd_hist_2 = debugger_cli_common.CommandHistory(limit=3)\n self.assertEqual([\"help 2\", \"help 3\", \"help 4\"],\n cmd_hist_2.most_recent_n(3))\n\n with open(self._history_file_path, \"rt\") as f:\n self.assertEqual(\n [\"help 2\\n\", \"help 3\\n\", \"help 4\\n\"], f.readlines())\n\n def testCommandHistoryHandlesReadingIOErrorGracoiusly(self):\n with open(self._history_file_path, \"wt\") as f:\n f.write(\"help\\n\")\n\n # Change file to not readable by anyone.\n os.chmod(self._history_file_path, 0)\n\n # The creation of a CommandHistory object should not error out.\n debugger_cli_common.CommandHistory(limit=3)\n\n def testCommandHistoryHandlesWritingIOErrorGracoiusly(self):\n with open(self._history_file_path, \"wt\") as f:\n f.write(\"help\\n\")\n\n # Change file to read-only.\n os.chmod(self._history_file_path,\n stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)\n\n # Reading from the file should still work.\n cmd_hist_2 = debugger_cli_common.CommandHistory(limit=3)\n self.assertEqual([\"help\"], cmd_hist_2.most_recent_n(1))\n\n # Writing should no longer work, but it should fail silently and\n # the within instance-command history should still work.\n cmd_hist_2.add_command(\"foo\")\n self.assertEqual([\"help\", \"foo\"], cmd_hist_2.most_recent_n(2))\n\n cmd_hist_3 = debugger_cli_common.CommandHistory(limit=3)\n self.assertEqual([\"help\"], cmd_hist_3.most_recent_n(1))\n\n\nclass MenuNodeTest(test_util.TensorFlowTestCase):\n\n def testCommandTypeConstructorSucceeds(self):\n menu_node = debugger_cli_common.MenuItem(\"water flower\", \"water_flower\")\n\n self.assertEqual(\"water flower\", menu_node.caption)\n self.assertEqual(\"water_flower\", menu_node.content)\n\n def testDisableWorks(self):\n menu_node = debugger_cli_common.MenuItem(\"water flower\", \"water_flower\")\n self.assertTrue(menu_node.is_enabled())\n\n menu_node.disable()\n self.assertFalse(menu_node.is_enabled())\n menu_node.enable()\n self.assertTrue(menu_node.is_enabled())\n\n def testConstructAsDisabledWorks(self):\n menu_node = debugger_cli_common.MenuItem(\n \"water flower\", \"water_flower\", enabled=False)\n self.assertFalse(menu_node.is_enabled())\n\n menu_node.enable()\n self.assertTrue(menu_node.is_enabled())\n\n\nclass MenuTest(test_util.TensorFlowTestCase):\n\n def setUp(self):\n self.menu = debugger_cli_common.Menu()\n self.assertEqual(0, self.menu.num_items())\n\n self.node1 = debugger_cli_common.MenuItem(\"water flower\", \"water_flower\")\n self.node2 = debugger_cli_common.MenuItem(\n \"measure wavelength\", \"measure_wavelength\")\n self.menu.append(self.node1)\n self.menu.append(self.node2)\n self.assertEqual(2, self.menu.num_items())\n\n def testFormatAsSingleLineWithStrItemAttrsWorks(self):\n output = self.menu.format_as_single_line(\n prefix=\"Menu: \", divider=\", \", enabled_item_attrs=\"underline\")\n self.assertEqual([\"Menu: water flower, measure wavelength, \"], output.lines)\n self.assertEqual((6, 18, [self.node1, \"underline\"]),\n output.font_attr_segs[0][0])\n self.assertEqual((20, 38, [self.node2, \"underline\"]),\n output.font_attr_segs[0][1])\n self.assertEqual({}, output.annotations)\n\n def testFormatAsSingleLineWithListItemAttrsWorks(self):\n output = self.menu.format_as_single_line(\n prefix=\"Menu: \", divider=\", \", enabled_item_attrs=[\"underline\", \"bold\"])\n self.assertEqual([\"Menu: water flower, measure wavelength, \"], output.lines)\n self.assertEqual((6, 18, [self.node1, \"underline\", \"bold\"]),\n output.font_attr_segs[0][0])\n self.assertEqual((20, 38, [self.node2, \"underline\", \"bold\"]),\n output.font_attr_segs[0][1])\n self.assertEqual({}, output.annotations)\n\n def testFormatAsSingleLineWithNoneItemAttrsWorks(self):\n output = self.menu.format_as_single_line(prefix=\"Menu: \", divider=\", \")\n self.assertEqual([\"Menu: water flower, measure wavelength, \"], output.lines)\n self.assertEqual((6, 18, [self.node1]), output.font_attr_segs[0][0])\n self.assertEqual((20, 38, [self.node2]), output.font_attr_segs[0][1])\n self.assertEqual({}, output.annotations)\n\n def testInsertNode(self):\n self.assertEqual([\"water flower\", \"measure wavelength\"],\n self.menu.captions())\n\n node2 = debugger_cli_common.MenuItem(\"write poem\", \"write_poem\")\n self.menu.insert(1, node2)\n self.assertEqual([\"water flower\", \"write poem\", \"measure wavelength\"],\n self.menu.captions())\n\n output = self.menu.format_as_single_line(prefix=\"Menu: \", divider=\", \")\n self.assertEqual([\"Menu: water flower, write poem, measure wavelength, \"],\n output.lines)\n\n def testFormatAsSingleLineWithDisabledNode(self):\n node2 = debugger_cli_common.MenuItem(\n \"write poem\", \"write_poem\", enabled=False)\n self.menu.append(node2)\n\n output = self.menu.format_as_single_line(\n prefix=\"Menu: \", divider=\", \", disabled_item_attrs=\"bold\")\n self.assertEqual([\"Menu: water flower, measure wavelength, write poem, \"],\n output.lines)\n self.assertEqual((6, 18, [self.node1]), output.font_attr_segs[0][0])\n self.assertEqual((20, 38, [self.node2]), output.font_attr_segs[0][1])\n self.assertEqual((40, 50, [\"bold\"]), output.font_attr_segs[0][2])\n\n\nif __name__ == \"__main__\":\n googletest.main()\n" ]
[ [ "tensorflow.python.debug.cli.debugger_cli_common.CommandLineExit", "tensorflow.python.debug.cli.debugger_cli_common.RichTextLines", "tensorflow.python.platform.gfile.Remove", "tensorflow.python.platform.googletest.main", "tensorflow.python.debug.cli.debugger_cli_common.CommandHandlerRegistry", "tensorflow.python.debug.cli.debugger_cli_common.MenuItem", "tensorflow.python.platform.gfile.Open", "tensorflow.python.debug.cli.debugger_cli_common.wrap_rich_text_lines", "tensorflow.python.debug.cli.debugger_cli_common.Menu", "tensorflow.python.debug.cli.debugger_cli_common.CommandHistory", "tensorflow.python.debug.cli.debugger_cli_common.TabCompletionRegistry", "tensorflow.python.debug.cli.debugger_cli_common.regex_find" ] ]
yoshihikoueno/pdfminer-layout-scanner
[ "437f7f2329db79c0f794fe41f4156218a982cec5" ]
[ "pdf_layout_scanner/layout_scanner.py" ]
[ "#!/usr/bin/python3\n\nimport sys\nimport os\nfrom tqdm import tqdm\nfrom binascii import b2a_hex\nimport pandas as pd\nimport pickle\nfrom pdfminer.pdfparser import PDFParser\nfrom pdfminer.pdfdocument import PDFDocument, PDFNoOutlines\nfrom pdfminer.pdfpage import PDFPage\nfrom pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter\nfrom pdfminer.converter import PDFPageAggregator\nfrom pdfminer.layout import LAParams, LTTextBox, LTTextLine, LTFigure, LTImage, LTChar, LTPage\nfrom logging import getLogger, StreamHandler, Formatter, DEBUG, INFO, WARN\nformatter = Formatter('%(asctime)s %(name)s[%(levelname)s] %(message)s', \"%Y-%m-%d %H:%M:%S\")\nlogger = getLogger(__name__)\nlogger.setLevel(INFO)\nhandler = StreamHandler()\nhandler.setLevel(logger.getEffectiveLevel())\nhandler.setFormatter(formatter)\nlogger.addHandler(handler)\nlogger.propagate = False\n\ndef with_pdf(pdf_doc, fn, pdf_pwd, *args):\n \"\"\"Open the pdf document, and apply the function, returning the results\"\"\"\n result = None\n try:\n # open the pdf file\n fp = open(pdf_doc, \"rb\")\n # create a parser object associated with the file object\n parser = PDFParser(fp)\n # create a PDFDocument object that stores the document structure\n doc = PDFDocument(parser, pdf_pwd)\n # connect the parser and document objects\n parser.set_document(doc)\n\n if doc.is_extractable:\n # apply the function and return the result\n result = fn(doc, *args)\n\n # close the pdf file\n fp.close()\n except IOError:\n # the file doesn't exist or similar problem\n pass\n return result\n\n\n# Table of Contents\ndef _parse_toc(doc):\n \"\"\"With an open PDFDocument object, get the table of contents (toc) data\n [this is a higher-order function to be passed to with_pdf()]\"\"\"\n toc = []\n try:\n outlines = doc.get_outlines()\n for (level, title, dest, a, se) in outlines:\n toc.append((level, title))\n except PDFNoOutlines:\n pass\n return toc\n\n\ndef get_toc(pdf_doc, pdf_pwd=\"\"):\n \"\"\"Return the table of contents (toc), if any, for this pdf file\"\"\"\n return with_pdf(pdf_doc, _parse_toc, pdf_pwd)\n\n\n# Extracting Images\ndef write_file(folder, filename, filedata, flags=\"w\"):\n \"\"\"Write the file data to the folder and filename combination\n (flags: 'w' for write text, 'wb' for write binary, use 'a' instead of 'w' for append)\"\"\"\n if os.path.isdir(folder):\n file_obj = open(os.path.join(folder, filename), flags)\n file_obj.write(filedata)\n file_obj.close()\n\ndef determine_image_type(stream_first_4_bytes):\n \"\"\"Find out the image file type based on the magic number comparison of the first 4 (or 2) bytes\"\"\"\n file_type = None\n bytes_as_hex = str(b2a_hex(stream_first_4_bytes))\n if bytes_as_hex.startswith(\"ffd8\"):\n file_type = \".jpeg\"\n elif bytes_as_hex == \"89504e47\":\n file_type = \".png\"\n elif bytes_as_hex == \"47494638\":\n file_type = \".gif\"\n elif bytes_as_hex.startswith(\"424d\"):\n file_type = \".bmp\"\n return file_type\n\n\ndef save_image(lt_image, page_number, images_folder):\n \"\"\"Try to save the image data from this LTImage object, and return the file name, if successful\"\"\"\n if not lt_image.stream: raise RuntimeError\n\n file_stream = lt_image.stream.get_rawdata()\n if not file_stream: raise RuntimeError\n\n file_ext = determine_image_type(file_stream[0:4])\n if not file_ext: raise RuntimeError\n\n file_name = \"\".join([str(page_number), \"_\", lt_image.name, file_ext])\n write_file(images_folder, file_name, file_stream, flags=\"wb\")\n return file_name\n\n\n# Extracting Text\ndef to_bytestring(s, enc=\"utf-8\"):\n \"\"\"Convert the given unicode string to a bytestring, using the standard encoding,\n unless it's already a bytestring\"\"\"\n if s:\n if isinstance(s, str):\n return s\n else:\n return s.encode(enc)\n\n\ndef update_page_text(df, lt_obj, pct=0.2, logger=logger):\n \"\"\"\n Use the bbox x0,x1 values within pct% to produce lists of associated text within the hash\n\n df:\n cols = [x0, y0, x1, y1, class, objs, str]\n \"\"\"\n if df is None: df = pd.DataFrame(columns=['x0', 'y0', 'x1', 'y1', 'class', 'objs', 'str'])\n\n if isinstance(lt_obj, (LTTextLine, LTTextBox)): store_new_line(df, lt_obj, pct, logger)\n else:\n raise NotImplementedError(lt_obj)\n return df\n\ndef store_new_line(df, lt_obj, pct, logger=logger):\n '''\n store a new line to df\n '''\n x0, y0, x1, y1 = lt_obj.bbox\n candidates = df[\n (df['class'] == lt_obj.__class__)\n & (df['x0'] >= x0 * (1 - pct))\n & (df['x0'] <= x0 * (1 + pct))\n & (df['x1'] >= x1 * (1 - pct))\n & (df['x1'] <= x1 * (1 + pct))\n & (df['y1'] <= y0)\n ]\n\n if candidates.shape[0] > 0:\n if candidates.shape[0] > 1:\n logger.warn('candidates has shape {}'.format(candidates.shape))\n target = candidates.iloc[0]\n df.at[target.name, 'y1'] = y1\n df.at[target.name, 'objs'].append(lt_obj)\n df.at[target.name, 'str'].append(to_bytestring(lt_obj.get_text()))\n else:\n df.loc[0 if pd.isnull(df.index.max()) else df.index.max() + 1] = [\n *lt_obj.bbox, lt_obj.__class__, [lt_obj], [to_bytestring(lt_obj.get_text())]\n ]\n return df\n\ndef parse_lt_objs(\n lt_objs, page_number, images_folder, text_content=None,\n return_df=False, progressbar=False,\n logger=logger,\n):\n \"\"\"Iterate through the list of LT* objects and capture the text or image data contained in each\"\"\"\n if text_content is None:\n text_content = []\n\n if progressbar:\n generator = tqdm(lt_objs, desc='parse objs')\n else:\n generator = lt_objs\n\n page_text = None\n # k=(x0, x1) of the bbox, v=list of text strings within that bbox width (physical column)\n for lt_obj in generator:\n if isinstance(lt_obj, (LTTextBox, LTTextLine, LTChar)):\n # text, so arrange is logically based on its column width\n page_text = update_page_text(page_text, lt_obj)\n elif isinstance(lt_obj, LTImage):\n # an image, so save it to the designated folder, and note its place in the text\n try:\n saved_file = save_image(lt_obj, page_number, images_folder)\n # use html style <img /> tag to mark the position of the image within the text\n text_content.append(\n '<img src=\"' + os.path.join(images_folder, saved_file) + '\" />'\n )\n except (IOError, RuntimeError):\n logger.error(\"failed to save image on page{} {}\".format(page_number, lt_obj))\n elif isinstance(lt_obj, LTFigure):\n # LTFigure objects are containers for other LT* objects, so recurse through the children\n text_content.append(\n parse_lt_objs(\n lt_obj, page_number, images_folder, text_content,\n return_df=return_df, progressbar=progressbar,\n )\n )\n\n if page_text is None:\n if return_df:\n return pd.DataFrame()\n else: return ''\n\n if return_df:\n text_content.append(page_text)\n return pd.concat(text_content)\n else:\n page_text = page_text.sort_values('y0')\n page_text = page_text['str'].apply(lambda x: text_content.append(''.join(x)))\n return \"\\n\".join(text_content)\n\n\n# Processing Pages\ndef _parse_pages(doc, images_folder, return_df=False, progressbar=False):\n \"\"\"With an open PDFDocument object, get the pages and parse each one\n [this is a higher-order function to be passed to with_pdf()]\"\"\"\n rsrcmgr = PDFResourceManager()\n laparams = LAParams(detect_vertical=True, all_texts=True)\n # all_texts will enable layout analysis in LTFigure objs\n device = PDFPageAggregator(rsrcmgr, laparams=laparams)\n interpreter = PDFPageInterpreter(rsrcmgr, device)\n\n if progressbar: generator = tqdm(enumerate(PDFPage.create_pages(doc)), desc='pages')\n else: generator = enumerate(PDFPage.create_pages(doc))\n\n text_content = []\n for i, page in generator:\n interpreter.process_page(page)\n # receive the LTPage object for this page\n layout = device.get_result()\n # layout is an LTPage object which may contain child objects like LTTextBox, LTFigure, LTImage, etc.\n text_content.append(\n parse_lt_objs(\n layout, (i + 1), images_folder,\n return_df=return_df,\n progressbar=progressbar,\n )\n )\n\n if return_df: return pd.concat(text_content)\n else: return text_content\n\ndef _get_page_size(doc, images_folder):\n \"\"\"With an open PDFDocument object, get the pages and parse each one\n [this is a higher-order function to be passed to with_pdf()]\"\"\"\n rsrcmgr = PDFResourceManager()\n laparams = LAParams(detect_vertical=True, all_texts=True)\n # all_texts will enable layout analysis in LTFigure objs\n device = PDFPageAggregator(rsrcmgr, laparams=laparams)\n interpreter = PDFPageInterpreter(rsrcmgr, device)\n\n sizes = []\n for i, page in enumerate(PDFPage.create_pages(doc)):\n interpreter.process_page(page)\n # receive the LTPage object for this page\n layout = device.get_result()\n # layout is an LTPage object which may contain child objects like LTTextBox, LTFigure, LTImage, etc.\n sizes.append(layout.cropbox)\n return sizes\n\n\ndef get_pages(pdf_doc, pdf_pwd=\"\", images_folder=\"/tmp\", return_df=False, progressbar=False):\n \"\"\"Process each of the pages in this pdf file and return a list of strings representing the text found in each page\"\"\"\n return with_pdf(pdf_doc, _parse_pages, pdf_pwd, images_folder, return_df, progressbar)\n\ndef get_sizes(pdf_doc, pdf_pwd=\"\"):\n '''get the sizes of each page'''\n return with_pdf(pdf_doc, _get_page_size, pdf_pwd)\n" ]
[ [ "pandas.DataFrame", "pandas.concat" ] ]
medjebbar/deepchem
[ "d636878164abb0562e3f5a9f2f187d3b5a5a097b" ]
[ "deepchem/feat/molecule_featurizers/rdkit_descriptors.py" ]
[ "\"\"\"\nBasic molecular features.\n\"\"\"\n\nimport numpy as np\n\nfrom deepchem.utils.typing import RDKitMol\nfrom deepchem.feat.base_classes import MolecularFeaturizer\n\n\nclass RDKitDescriptors(MolecularFeaturizer):\n \"\"\"RDKit descriptors.\n\n This class computes a list of chemical descriptors like\n molecular weight, number of valence electrons, maximum and\n minimum partial charge, etc using RDKit.\n\n Attributes\n ----------\n descriptors: List[str]\n List of RDKit descriptor names used in this class.\n\n Note\n ----\n This class requires RDKit to be installed.\n\n Examples\n --------\n >>> import deepchem as dc\n >>> smiles = ['CC(=O)OC1=CC=CC=C1C(=O)O']\n >>> featurizer = dc.feat.RDKitDescriptors()\n >>> features = featurizer.featurize(smiles)\n >>> type(features[0])\n <class 'numpy.ndarray'>\n >>> features[0].shape\n (208,)\n\n \"\"\"\n\n def __init__(self, use_fragment=True, ipc_avg=True):\n \"\"\"Initialize this featurizer.\n\n Parameters\n ----------\n use_fragment: bool, optional (default True)\n If True, the return value includes the fragment binary descriptors like 'fr_XXX'.\n ipc_avg: bool, optional (default True)\n If True, the IPC descriptor calculates with avg=True option.\n Please see this issue: https://github.com/rdkit/rdkit/issues/1527.\n \"\"\"\n self.use_fragment = use_fragment\n self.ipc_avg = ipc_avg\n self.descriptors = []\n self.descList = []\n\n def _featurize(self, mol: RDKitMol) -> np.ndarray:\n \"\"\"\n Calculate RDKit descriptors.\n\n Parameters\n ----------\n mol: rdkit.Chem.rdchem.Mol\n RDKit Mol object\n\n Returns\n -------\n np.ndarray\n 1D array of RDKit descriptors for `mol`.\n The length is `len(self.descriptors)`.\n \"\"\"\n # initialize\n if len(self.descList) == 0:\n try:\n from rdkit.Chem import Descriptors\n for descriptor, function in Descriptors.descList:\n if self.use_fragment is False and descriptor.startswith('fr_'):\n continue\n self.descriptors.append(descriptor)\n self.descList.append((descriptor, function))\n except ModuleNotFoundError:\n raise ImportError(\"This class requires RDKit to be installed.\")\n\n # check initialization\n assert len(self.descriptors) == len(self.descList)\n\n features = []\n for desc_name, function in self.descList:\n if desc_name == 'Ipc' and self.ipc_avg:\n feature = function(mol, avg=True)\n else:\n feature = function(mol)\n features.append(feature)\n return np.asarray(features)\n" ]
[ [ "numpy.asarray" ] ]
w111liang222/fulaoban
[ "a3fec75845295a8ea2d709fb90b83e266293e2ff" ]
[ "parser.py" ]
[ "import os\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\nfrom laserscan import LaserScan\nfrom poseloader import PoseLoader\nfrom scipy.spatial.transform import Rotation as R\n\nEXTENSIONS_SCAN = ['.bin']\nEXTENSIONS_POSE = ['.txt']\n\n\ndef is_scan(filename):\n return any(filename.endswith(ext) for ext in EXTENSIONS_SCAN)\n\n\ndef is_pose(filename):\n return any(filename.endswith(ext) for ext in EXTENSIONS_POSE)\n\n\nclass SlamKitti(Dataset):\n\n def __init__(self, root, # directory where data is\n sequences, # sequences for this data (e.g. [1,3,4,6])\n sensor, # sensor to parse scans from\n max_points=150000, # max number of points present in dataset\n shuffle=False,\n gt=True): # send ground truth?\n # save deats\n self.root = os.path.join(root, \"sequences\")\n self.sequences = sequences\n self.sensor = sensor\n self.shuffle = shuffle\n self.sensor_img_H = sensor[\"img_prop\"][\"height\"]\n self.sensor_img_W = sensor[\"img_prop\"][\"width\"]\n self.sensor_img_means = torch.tensor(sensor[\"img_means\"],\n dtype=torch.float)\n self.sensor_img_stds = torch.tensor(sensor[\"img_stds\"],\n dtype=torch.float)\n self.sensor_fov_up = sensor[\"fov_up\"]\n self.sensor_fov_down = sensor[\"fov_down\"]\n self.max_points = max_points\n self.gt = gt\n\n # make sure directory exists\n if os.path.isdir(self.root):\n print(\"Sequences folder exists! Using sequences from %s\" % self.root)\n else:\n raise ValueError(\"Sequences folder doesn't exist! Exiting...\")\n\n # make sure sequences is a list\n assert(isinstance(self.sequences, list))\n\n # placeholder for filenames\n self.scan_files = []\n self.pose_files = []\n self.sequences_scan_num = [0]\n\n # fill in with names, checking that all sequences are complete\n for seq in self.sequences:\n # to string\n seq = '{0:02d}'.format(int(seq))\n\n print(\"parsing seq {}\".format(seq))\n\n # get paths for each\n scan_path = os.path.join(self.root, seq, \"velodyne\")\n pose_path = os.path.join(self.root, seq, \"pose_6dof\")\n\n # get files\n scan_files = [os.path.join(dp, f) for dp, dn, fn in os.walk(\n os.path.expanduser(scan_path)) for f in fn if is_scan(f)]\n pose_files = [os.path.join(dp, f) for dp, dn, fn in os.walk(\n os.path.expanduser(pose_path)) for f in fn if is_pose(f)]\n\n # check all scans have labels\n if self.gt:\n assert(len(scan_files) == len(pose_files))\n\n # extend list\n self.scan_files.extend(scan_files)\n self.pose_files.extend(pose_files)\n\n self.sequences_scan_num.append(\n self.sequences_scan_num[-1] + len(scan_files))\n\n # sort for correspondance\n self.scan_files.sort()\n self.pose_files.sort()\n\n print(\"Using {} scans from sequences {}\".format(len(self.scan_files),\n self.sequences))\n\n def getSingleItem(self, index):\n # get item in tensor shape\n scan_file = self.scan_files[index]\n if self.gt:\n pose_file = self.pose_files[index]\n\n # open a laserscan\n scan = LaserScan(project=True,\n H=self.sensor_img_H,\n W=self.sensor_img_W,\n fov_up=self.sensor_fov_up,\n fov_down=self.sensor_fov_down)\n\n pose = PoseLoader()\n # open and obtain scan\n scan.open_scan(scan_file)\n if self.gt:\n pose_vec = pose.open_pose(pose_file)\n else:\n pose_vec = np.zeros((1, 6))\n\n # get points and labels\n proj_range = torch.from_numpy(scan.proj_range).clone()\n proj_xyz = torch.from_numpy(scan.proj_xyz).clone()\n proj_remission = torch.from_numpy(scan.proj_remission).clone()\n proj_mask = torch.from_numpy(scan.proj_mask)\n\n proj = torch.cat([proj_range.unsqueeze(0).clone(),\n proj_xyz.clone().permute(2, 0, 1),\n proj_remission.unsqueeze(0).clone()])\n proj = (proj - self.sensor_img_means[:, None, None]\n ) / self.sensor_img_stds[:, None, None]\n proj = proj * proj_mask.float()\n return proj, pose_vec\n\n def get_delta_pose(self, pose0, pose1):\n Rm0 = R.from_rotvec(pose0[3:])\n Rm1 = R.from_rotvec(pose1[3:])\n Rm0_inv = Rm0.inv()\n\n t0_inv = -np.dot(Rm0_inv.as_matrix(), pose0[0:3])\n delta_t = t0_inv + np.dot(Rm0_inv.as_matrix(), pose1[0:3])\n delta_r = (Rm0_inv*Rm1).as_euler('zxy', degrees=True)\n delta_pose = np.concatenate([delta_t, delta_r])\n\n # return\n delta_pose_t = torch.from_numpy(delta_pose).clone()\n return delta_pose_t\n\n def __getitem__(self, index):\n for i, seq_i in enumerate(self.sequences_scan_num):\n if index == (seq_i - 1):\n index = index - 2\n break\n if index == (seq_i - 2):\n index = index - 1\n break\n scan0, pose0 = self.getSingleItem(index)\n scan1, pose1 = self.getSingleItem(index + 1)\n scan2, pose2 = self.getSingleItem(index + 2)\n delta_pose01 = self.get_delta_pose(pose0, pose1)\n delta_pose02 = self.get_delta_pose(pose1, pose2)\n\n return scan0, scan1, scan2, delta_pose01, delta_pose02\n\n def __len__(self):\n return len(self.scan_files) - 1\n\n\nclass Parser():\n # standard conv, BN, relu\n def __init__(self,\n root, # directory for data\n train_sequences, # sequences to train\n valid_sequences, # sequences to validate.\n test_sequences, # sequences to test (if none, don't get)\n sensor, # sensor to use\n max_points, # max points in each scan in entire dataset\n batch_size, # batch size for train and val\n workers, # threads to load data\n gt=True, # get gt?\n shuffle_train=True): # shuffle training set?\n super(Parser, self).__init__()\n\n # if I am training, get the dataset\n self.root = root\n self.train_sequences = train_sequences\n self.valid_sequences = valid_sequences\n self.test_sequences = test_sequences\n self.sensor = sensor\n self.max_points = max_points\n self.batch_size = batch_size\n self.workers = workers\n self.gt = gt\n self.shuffle_train = shuffle_train\n\n # Data loading code\n self.train_dataset = SlamKitti(root=self.root,\n sequences=self.train_sequences,\n sensor=self.sensor,\n max_points=max_points,\n shuffle=self.shuffle_train,\n gt=self.gt)\n\n self.trainloader = torch.utils.data.DataLoader(self.train_dataset,\n batch_size=self.batch_size,\n shuffle=self.shuffle_train,\n num_workers=self.workers,\n pin_memory=True,\n drop_last=True)\n assert len(self.trainloader) > 0\n self.trainiter = iter(self.trainloader)\n\n self.valid_dataset = SlamKitti(root=self.root,\n sequences=self.valid_sequences,\n sensor=self.sensor,\n max_points=max_points,\n shuffle=False,\n gt=self.gt)\n\n self.validloader = torch.utils.data.DataLoader(self.valid_dataset,\n batch_size=self.batch_size,\n shuffle=False,\n num_workers=self.workers,\n pin_memory=True,\n drop_last=True)\n assert len(self.validloader) > 0\n self.validiter = iter(self.validloader)\n\n if self.test_sequences:\n self.test_dataset = SlamKitti(root=self.root,\n sequences=self.test_sequences,\n sensor=self.sensor,\n max_points=max_points,\n shuffle=False,\n gt=False)\n\n self.testloader = torch.utils.data.DataLoader(self.test_dataset,\n batch_size=self.batch_size,\n shuffle=False,\n num_workers=self.workers,\n pin_memory=True,\n drop_last=True)\n assert len(self.testloader) > 0\n self.testiter = iter(self.testloader)\n\n def get_train_batch(self):\n scans = self.trainiter.next()\n return scans\n\n def get_train_set(self):\n return self.trainloader\n\n def get_valid_batch(self):\n scans = self.validiter.next()\n return scans\n\n def get_valid_set(self):\n return self.validloader\n\n def get_test_batch(self):\n scans = self.testiter.next()\n return scans\n\n def get_test_set(self):\n return self.testloader\n\n def get_train_size(self):\n return len(self.trainloader)\n\n def get_valid_size(self):\n return len(self.validloader)\n\n def get_test_size(self):\n return len(self.testloader)\n" ]
[ [ "numpy.concatenate", "numpy.zeros", "torch.from_numpy", "torch.tensor", "torch.utils.data.DataLoader", "scipy.spatial.transform.Rotation.from_rotvec" ] ]
deepjets/deepjets
[ "fc9c610d4fd80975d8d25eb0d7cd41d7dd318c75" ]
[ "deepjets/preprocessing.py" ]
[ "import numpy as np\nfrom skimage import transform\n\n\ndef translate(jet_csts, subjets):\n \"\"\"Translate constituents and jets, leading subjet at (eta, phi) = (0, 0).\n \"\"\"\n # Translate constituents\n jet_csts['eta'] -= subjets['eta'][0]\n jet_csts['phi'] -= subjets['phi'][0]\n # Ensure phi in [-pi, pi]\n jet_csts['phi'] = np.mod(jet_csts['phi'] + np.pi, 2*np.pi) - np.pi\n # Translate jets\n subjets['eta'] -= subjets['eta'][0]\n subjets['phi'] -= subjets['phi'][0]\n # Ensure phi in [-pi, pi]\n subjets['phi'] = np.mod(subjets['phi'] + np.pi, 2*np.pi) - np.pi\n\n\ndef pixel_edges(jet_size=1.0, pixel_size=(0.1, 0.1), border_size=0.25):\n \"\"\"Return pixel edges required to contain all subjets.\n\n border_size is interpreted as a fraction of the jet_size\n \"\"\"\n im_edge = (1. + border_size) * jet_size\n return (np.arange(-im_edge, im_edge+pixel_size[0], pixel_size[0]),\n np.arange(-im_edge, im_edge+pixel_size[1], pixel_size[1]))\n\n\ndef pixelize(jet_csts, edges, cutoff=0.1):\n \"\"\"Return eta-phi histogram of transverse energy deposits.\n\n Optionally set all instensities below cutoff to zero.\n \"\"\"\n image, _, _ = np.histogram2d(\n jet_csts['eta'], jet_csts['phi'],\n bins=(edges[0], edges[1]),\n weights=jet_csts['ET'] * (jet_csts['ET'] > cutoff))\n return image\n\n\ndef rotate_image(image, subjets):\n \"\"\"Return rotated and repixelised image array.\n\n Rotation puts subleading subjet or first principle component at -pi/2.\n Repixelisation interpolates with cubic spline.\n \"\"\"\n # Use subleading subject information to rotate\n if len(subjets) > 1:\n theta = np.arctan2(subjets['phi'][1], subjets['eta'][1])\n theta = -90.0-(theta*180.0/np.pi)\n return transform.rotate(image, theta, order=3)\n\n # Use principle component of image intensity to rotate\n width, height = image.shape\n pix_coords = np.array([[i, j] for i in range(-width+1, width, 2)\n for j in range(-height+1, height, 2)])\n covX = np.cov(pix_coords, aweights=np.reshape(image, (width*height)),\n rowvar=0, bias=1)\n e_vals, e_vecs = np.linalg.eigh(covX)\n pc = e_vecs[:,-1]\n theta = np.arctan2(pc[1], pc[0])\n theta = -90.0-(theta*180.0/np.pi)\n t_image = transform.rotate(image, theta, order=3)\n # Check orientation of principle component\n pix_bot = np.sum(t_image[:, :-(-height//2)])\n pix_top = np.sum(t_image[:, (height//2):])\n if pix_top > pix_bot:\n t_image = transform.rotate(t_image, 180.0, order=3)\n theta += 180.0\n return t_image\n\n\ndef reflect_image(image, subjets):\n \"\"\"Return reflected image array.\n\n Reflection puts subsubleading subjet or highest intensity on right side.\n \"\"\"\n width, height = image.shape\n if len(subjets) > 2:\n # Use subsubleading subject information to find parity\n theta = np.arctan2(subjets['phi'][1], subjets['eta'][1])\n theta = -(np.pi/2)-theta\n parity = np.sign(np.cos(-theta)*subjets['eta'][2] +\n np.sin(-theta)*subjets['phi'][2])\n else:\n # Use intensity to find parity\n pix_l = np.sum(image[:-(-width//2)].flatten())\n pix_r = np.sum(image[(width//2):].flatten())\n parity = np.sign(pix_r - pix_l)\n\n if parity >= 0:\n return image\n t_image = np.array(image)\n for i in range(width):\n t_image[i] = image[-i-1]\n return t_image\n\n\ndef zoom_image_fixed_size(image, zoom):\n \"\"\"Return rescaled and cropped image array.\n \"\"\"\n if zoom < 1:\n raise ValueError(\"Zoom scale factor must be at least 1.\")\n elif zoom == 1:\n # copy\n return np.array(image)\n\n width, height = image.shape\n t_width = int(np.ceil(zoom*width))\n t_height = int(np.ceil(zoom*height))\n if t_width//2 != width//2:\n t_width -= 1\n if t_height//2 != height//2:\n t_height -= 1\n t_image = transform.resize(image, (t_width, t_height), order=3)\n return t_image[(t_width-width)/2:(t_width+width)/2,\n (t_height-height)/2:(t_height+height)/2]\n\n\ndef zoom_image(image, zoom, out_width=25):\n \"\"\"Return rescaled and cropped image array with width out_width.\n \"\"\"\n if zoom < 1:\n raise ValueError(\"Zoom scale factor must be at least 1.\")\n\n width, height = image.shape\n #if width < out_width:\n # raise ValueError(\n # \"image width before zooming ({0}) is less \"\n # \"than requested output width ({1})\".format(width, out_width))\n out_height = int(np.rint(float(out_width * height) / width))\n t_width = int(np.rint(out_width * zoom))\n t_height = int(np.rint(out_height * zoom))\n if t_width // 2 != out_width // 2:\n t_width += 1\n if t_height // 2 != out_height // 2:\n t_height += 1\n # zoom with cubic interpolation\n t_image = transform.resize(image, (t_width, t_height), order=3)\n # crop\n return t_image[(t_width - out_width) / 2:(t_width + out_width) / 2,\n (t_height - out_height) / 2:(t_height + out_height) / 2]\n\n\ndef normalize_image(image):\n \"\"\"Return normalized image array: sum(I**2) == 1.\n \"\"\"\n return image / np.sum(image**2)\n\n\ndef preprocess(subjets, constits, edges,\n cutoff=0.1,\n rotate=True,\n reflect=True,\n zoom=False,\n out_width=25,\n normalize=True):\n translate(constits, subjets)\n image = pixelize(constits, edges)\n if rotate:\n image = rotate_image(image, subjets)\n if reflect:\n image = reflect_image(image, subjets)\n image = zoom_image(image, zoom if zoom is not False else 1., out_width)\n if normalize:\n image = normalize_image(image)\n return image\n" ]
[ [ "numpy.histogram2d", "numpy.array", "numpy.ceil", "numpy.sin", "numpy.reshape", "numpy.sum", "numpy.linalg.eigh", "numpy.rint", "numpy.sign", "numpy.arange", "numpy.arctan2", "numpy.cos", "numpy.mod" ] ]
nuo010/pyefun
[ "ac2290d4bcc8de16c195d2782f3eacd26e5e6ed4" ]
[ "pyefun/chartUtil.py" ]
[ "#-*- coding: utf-8 -*-\nimport random,io\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom .public import *\n\n\n图表颜色 = [\n '#F0F8FF', '#FAEBD7', '#00FFFF', '#7FFFD4', '#F0FFFF', '#F5F5DC', '#FFE4C4', '#FFEBCD', '#8A2BE2', '#A52A2A',\n '#DEB887', '#5F9EA0', '#7FFF00', '#D2691E', '#FF7F50', '#6495ED', '#FFF8DC', '#DC143C', '#00FFFF', '#008B8B',\n '#B8860B', '#A9A9A9', '#006400', '#BDB76B', '#8B008B', '#556B2F', '#FF8C00', '#9932CC', '#8B0000', '#E9967A',\n '#8FBC8F', '#483D8B', '#2F4F4F', '#00CED1', '#9400D3', '#FF1493', '#00BFFF', '#696969', '#1E90FF', '#B22222',\n '#FFFAF0', '#228B22', '#FF00FF', '#DCDCDC', '#F8F8FF', '#FFD700', '#DAA520', '#808080', '#008000', '#ADFF2F',\n '#F0FFF0', '#FF69B4', '#CD5C5C', '#4B0082', '#F0E68C', '#E6E6FA', '#FFF0F5', '#7CFC00', '#FFFACD', '#ADD8E6',\n '#F08080', '#E0FFFF', '#90EE90', '#D3D3D3', '#FFB6C1', '#FFA07A', '#20B2AA', '#87CEFA', '#778899', '#B0C4DE',\n '#00FF00', '#32CD32', '#FAF0E6', '#FF00FF', '#800000', '#66CDAA', '#BA55D3', '#9370DB', '#3CB371', '#7B68EE',\n '#00FA9A', '#48D1CC', '#C71585', '#191970', '#F5FFFA', '#FFE4E1', '#FFE4B5', '#FFDEAD', '#FDF5E6', '#808000',\n '#6B8E23', '#FFA500', '#FF4500', '#DA70D6', '#EEE8AA', '#98FB98', '#AFEEEE', '#DB7093', '#FFEFD5', '#FFDAB9',\n '#CD853F', '#FFC0CB', '#DDA0DD', '#B0E0E6', '#800080', '#FF0000', '#BC8F8F', '#4169E1', '#8B4513', '#FA8072',\n '#FAA460', '#2E8B57', '#FFF5EE', '#A0522D', '#C0C0C0', '#87CEEB', '#6A5ACD', '#708090', '#FFFAFA', '#00FF7F',\n '#4682B4', '#D2B48C', '#008080', '#D8BFD8', '#FF6347', '#40E0D0', '#EE82EE', '#F5DEB3', '#F5F5F5', '#FFFF00',\n '#9ACD32']\n\n\nclass 圆饼图:\n\n def __init__(self,标签列表=[],数值列表=[],颜色列表=[],间隔列表=[],起始角度=90,数值显示距离=0.6,保留小数位数=2,阴影=False,显示图例=True,宽高=()):\n self.plt = plt\n self.标签列表 = 标签列表\n self.数值列表 = 数值列表\n self.颜色列表 = 颜色列表\n self.间隔列表 = 间隔列表\n self.起始角度 = 起始角度 #逆时针起始角度设置\n self.数值显示位置 = 数值显示距离 #0-1,数值距圆心半径倍数距离\n self.保留小数位数 = 保留小数位数 #数值保留固定小数位\n self.显示阴影 = 阴影 #设置阴影\n self.宽高 = ()\n self.显示图例 = 显示图例\n\n @异常处理返回类型逻辑型\n def 生成(self,保存地址='',显示=True):\n '返回:图片二进制,标签列表,比例列表'\n fig = self.plt.figure()\n self.plt.rcParams['font.sans-serif'] = ['SimHei'] # 解决中文乱码\n if self.宽高:\n self.plt.figure(figsize=(self.宽高[0],self.宽高[1]))\n\n if not self.标签列表 and not self.数值列表:\n self.标签列表 = ['张三','李四','王五']\n self.数值列表 = [111,222,333]\n\n 数量 = len(self.标签列表)\n if not self.颜色列表 or len(self.颜色列表)<数量:\n 颜色列表 = random.sample(图表颜色, 数量)\n else:\n 颜色列表 = self.颜色列表\n\n if not self.间隔列表 or len(self.间隔列表)<数量:\n self.间隔列表 = [0 for i in range(数量)]\n\n patches, text1, text2 = self.plt.pie(self.数值列表,\n explode=self.间隔列表,\n labels=self.标签列表,\n colors=颜色列表,\n autopct='%.{}f%%'.format(self.保留小数位数),\n shadow=self.显示阴影,\n startangle=self.起始角度,\n pctdistance=self.数值显示位置)\n self.plt.axis('equal')\n\n if self.显示图例:\n self.plt.legend()\n\n if 保存地址:\n self.plt.savefig(保存地址)\n\n if 显示:\n self.plt.show()\n\n canvas=fig.canvas\n buffer = io.BytesIO()\n canvas.print_png(buffer)\n data = buffer.getvalue()\n buffer.close()\n\n 标签列表=[]\n 比例列表=[]\n for x in range(len(text1)):\n 标签列表.append(text1[x].get_text())\n 比例列表.append(text2[x].get_text())\n\n return data,标签列表,比例列表\n\n\n\nclass 柱状图:\n def __init__(self,宽高=(),标题=\"\",横向标题=\"\",纵向标题=\"\",标签列表=[],数值列表=[],名称列表=[],颜色列表=[],柱宽=0.25,标题字体大小=20,显示项目名称=True):\n self.np = np\n self.plt = plt\n self.宽高 = 宽高\n self.标题 = 标题\n self.横向标题 = 横向标题\n self.纵向标题 = 纵向标题\n self.标签列表 = 标签列表\n self.数值列表 = [数值列表] if 数值列表 else []\n self.颜色列表 = 颜色列表\n self.名称列表 = 名称列表\n self.柱宽 = 柱宽\n self.显示项目名称 = 显示项目名称\n self.标题字体大小 = 标题字体大小\n\n @异常处理返回类型逻辑型\n def 加入新数值列表(self,数值列表):\n self.数值列表.append(数值列表)\n\n @异常处理返回类型逻辑型\n def 生成(self, 保存地址='', 显示=True):\n self.plt.rcParams['font.sans-serif'] = 'Microsoft YaHei'\n fig = self.plt.figure()\n if not self.标签列表 and not self.数值列表:\n self.标签列表 = ['a', 'b', 'c', 'd', 'e']\n self.数值列表 = [[33, 25, 15, 10, 3],[13, 15, 13, 5, 8]]\n\n 数量 = len(self.标签列表)\n x = self.np.arange(数量)\n if self.宽高:\n self.plt.figure(figsize=(self.宽高[0], self.宽高[1]))\n\n if not self.名称列表 or len(self.名称列表)<len(self.数值列表):\n self.名称列表 = ['名称'+str(i) for i in range(数量)]\n\n if not self.颜色列表 or len(self.颜色列表) < 数量:\n 颜色列表 = random.sample(图表颜色, 数量)\n else:\n 颜色列表 = self.颜色列表\n\n for i in range(len(self.数值列表)):\n d = {'tick_label':self.标签列表} if i == 0 else {}\n if self.显示项目名称:\n d['label'] = self.名称列表[i]\n self.plt.bar(x+i*self.柱宽, self.数值列表[i], width=self.柱宽, color=颜色列表[i],**d)\n\n for a, b in zip(x, self.数值列表[i]):\n self.plt.text(a+i*self.柱宽, b + 0.1, b, ha='center', va='bottom')\n\n self.plt.xticks()\n if self.显示项目名称:\n self.plt.legend(loc=\"upper right\") # (左.left 右.right)防止label和图像重合显示不出来\n self.plt.ylabel(self.纵向标题)\n self.plt.xlabel(self.横向标题)\n self.plt.title(self.标题,fontdict = {'fontsize':self.标题字体大小})\n\n if 保存地址:\n self.plt.savefig(保存地址)\n\n if 显示:\n self.plt.show()\n canvas = fig.canvas\n buffer = io.BytesIO()\n canvas.print_png(buffer)\n data = buffer.getvalue()\n buffer.close()\n return data\n\n\n\nclass 横向柱状图:\n def __init__(self,宽高=(),标题=\"\",横向标题=\"\",纵向标题=\"\",标签列表=[],数值列表=[],颜色值=\"\",标题字体大小=20,显示项目名称=True):\n self.np = np\n self.plt = plt\n self.宽高 = 宽高\n self.标题 = 标题\n self.横向标题 = 横向标题\n self.纵向标题 = 纵向标题\n self.标签列表 = 标签列表\n self.数值列表 = 数值列表\n self.颜色 = 颜色值\n self.标题字体大小 = 标题字体大小\n\n @异常处理返回类型逻辑型\n def 生成(self, 保存地址='', 显示=True):\n self.plt.rcParams['font.sans-serif'] = 'Microsoft YaHei'\n fig = self.plt.figure()\n if self.宽高:\n self.plt.figure(figsize=(self.宽高[0], self.宽高[1]))\n\n if not self.颜色:\n self.颜色 = random.choice(图表颜色)\n\n if not self.标签列表 and not self.数值列表:\n self.标签列表 = ['a', 'b', 'c', 'd', 'e']\n self.数值列表 = [33, 25, 15, 10, 3]\n\n fig, ax = self.plt.subplots()\n ax.barh(self.标签列表, self.数值列表, color=self.颜色)\n labels = ax.get_xticklabels()\n self.plt.setp(labels, rotation=0, horizontalalignment='right')\n\n for a, b in zip(self.标签列表, self.数值列表):\n self.plt.text(b + 1, a, b, ha='center', va='center')\n\n self.plt.ylabel(self.纵向标题)\n self.plt.xlabel(self.横向标题)\n self.plt.title(self.标题,fontdict = {'fontsize':self.标题字体大小})\n\n if 保存地址:\n self.plt.savefig(保存地址)\n\n if 显示:\n self.plt.show()\n\n canvas = fig.canvas\n buffer = io.BytesIO()\n canvas.print_png(buffer)\n data = buffer.getvalue()\n buffer.close()\n return data\n\n\nclass 重叠柱状图:\n def __init__(self,宽高=(),标题=\"\",横向标题=\"\",纵向标题=\"\",标签列表=[],数值列表=[],名称列表=[],颜色列表=[],柱宽=None,标题字体大小=20,显示项目名称=True):\n self.np = np\n self.plt = plt\n self.宽高 = 宽高\n self.标题 = 标题\n self.横向标题 = 横向标题\n self.纵向标题 = 纵向标题\n self.标签列表 = 标签列表\n self.数值列表 = [数值列表] if 数值列表 else []\n self.颜色列表 = 颜色列表\n self.名称列表 = 名称列表\n self.柱宽 = 柱宽\n self.显示项目名称 = 显示项目名称\n self.标题字体大小 = 标题字体大小\n\n @异常处理返回类型逻辑型\n def 加入新数值列表(self,数值列表):\n self.数值列表.append(数值列表)\n\n @异常处理返回类型逻辑型\n def 生成(self, 保存地址='', 显示=True):\n self.plt.rcParams['font.sans-serif'] = 'Microsoft YaHei'\n fig = self.plt.figure()\n if not self.标签列表 and not self.数值列表:\n self.标签列表 = ['a', 'b', 'c', 'd', 'e']\n self.数值列表 = [[33, 25, 15, 10, 9],[13, 15, 13, 5, 8]]\n\n 数量 = len(self.标签列表)\n x = self.np.arange(数量)\n if self.宽高:\n self.plt.figure(figsize=(self.宽高[0], self.宽高[1]))\n\n if not self.名称列表 or len(self.名称列表)<len(self.数值列表):\n self.名称列表 = ['名称'+str(i) for i in range(数量)]\n\n if not self.颜色列表 or len(self.颜色列表) < 数量:\n 颜色列表 = random.sample(图表颜色, 数量)\n else:\n 颜色列表 = self.颜色列表\n\n for i in range(len(self.数值列表)):\n d = {'tick_label':self.标签列表} if i == 0 else {}\n if self.显示项目名称:\n d['label'] = self.名称列表[i]\n if self.柱宽:\n d['width'] = self.柱宽\n self.plt.bar(self.标签列表, self.数值列表[i], color=颜色列表[i],**d)\n for a, b in zip(x, self.数值列表[i]):\n self.plt.text(a, b + 0.1, b, ha='center', va='bottom')\n self.plt.xticks(self.np.arange(数量), self.标签列表, rotation=0, fontsize=10)\n\n if self.显示项目名称:\n self.plt.legend(loc=\"upper right\") # (左.left 右.right)防止label和图像重合显示不出来\n self.plt.ylabel(self.纵向标题)\n self.plt.xlabel(self.横向标题)\n self.plt.title(self.标题,fontdict = {'fontsize':self.标题字体大小})\n\n if 保存地址:\n self.plt.savefig(保存地址)\n\n if 显示:\n self.plt.show()\n\n canvas = fig.canvas\n buffer = io.BytesIO()\n canvas.print_png(buffer)\n data = buffer.getvalue()\n buffer.close()\n return data\n\n\n\nclass 折线图:\n def __init__(self,宽高=(),标题=\"\",横向标题=\"\",纵向标题=\"\",标签列表=[],数值列表=[],名称列表=[],颜色列表=[],标题字体大小=20,显示项目名称=True,显示数值=True,显示圆点=True):\n self.np = np\n self.plt = plt\n self.宽高 = 宽高\n self.标题 = 标题\n self.横向标题 = 横向标题\n self.纵向标题 = 纵向标题\n self.标签列表 = 标签列表\n self.数值列表 = [数值列表] if 数值列表 else []\n self.颜色列表 = 颜色列表\n self.名称列表 = 名称列表\n self.显示项目名称 = 显示项目名称\n self.标题字体大小 = 标题字体大小\n self.显示数值 = 显示数值\n self.显示圆点 = 显示圆点\n\n @异常处理返回类型逻辑型\n def 加入新数值列表(self,数值列表):\n self.数值列表.append(数值列表)\n\n @异常处理返回类型逻辑型\n def 生成(self, 保存地址='', 显示=True):\n self.plt.rcParams['font.sans-serif'] = 'Microsoft YaHei'\n fig = self.plt.figure()\n if not self.标签列表 and not self.数值列表:\n self.标签列表 = ['a', 'b', 'c', 'd', 'e']\n self.数值列表 = [[33, 25, 15, 10, 3],[13, 15, 13, 5, 8]]\n\n 数量 = len(self.标签列表)\n x = self.np.arange(数量)\n if self.宽高:\n self.plt.figure(figsize=(self.宽高[0], self.宽高[1]))\n\n if not self.名称列表 or len(self.名称列表)<len(self.数值列表):\n self.名称列表 = ['名称'+str(i) for i in range(数量)]\n\n if not self.颜色列表 or len(self.颜色列表) < 数量:\n 颜色列表 = random.sample(图表颜色, 数量)\n else:\n 颜色列表 = self.颜色列表\n\n for i in range(len(self.数值列表)):\n d = {}\n if self.显示项目名称:\n d['label'] = self.名称列表[i]\n if self.显示圆点:\n d['marker'] = '.'\n\n self.plt.plot(self.标签列表,self.数值列表[i],color=颜色列表[i],linewidth=1,mfc='w',markersize=10,mfcalt='b',**d)\n\n if self.显示数值:\n for a, b in zip(self.标签列表, self.数值列表[i]):\n plt.text(a, b, b, ha='center', va='bottom', fontsize=8)\n\n if self.显示项目名称:\n self.plt.legend(loc=\"upper right\") # (左.left 右.right)防止label和图像重合显示不出来\n self.plt.ylabel(self.纵向标题)\n self.plt.xlabel(self.横向标题)\n self.plt.title(self.标题,fontdict = {'fontsize':self.标题字体大小})\n\n #加虚线背景 透明度1 去掉是实线\n self.plt.grid(alpha=1,linestyle=':')\n\n if 保存地址:\n self.plt.savefig(保存地址)\n\n if 显示:\n self.plt.show()\n\n canvas = fig.canvas\n buffer = io.BytesIO()\n canvas.print_png(buffer)\n data = buffer.getvalue()\n buffer.close()\n return data" ]
[ [ "matplotlib.pyplot.text" ] ]
anetczuk/pybraingym
[ "4f930021d7802e88c75a1a0aed135dd4de66cc1b" ]
[ "src/pybraingym/interface.py" ]
[ "# MIT License\n#\n# Copyright (c) 2019 Arkadiusz Netczuk <[email protected]>\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\nfrom scipy import zeros\n\n\nclass Wrapper(object):\n \n def __init__(self, wrapped):\n self.wrapped = wrapped\n\n def __getattr__(self,attr):\n orig_attr = self.wrapped.__getattribute__(attr)\n return orig_attr\n\n\nclass ActionValueTableWrapper(Wrapper):\n \n def __init__(self, module):\n Wrapper.__init__(self, module)\n self.stateArray = zeros( module.numRows, dtype=int )\n\n def activate(self, inpt):\n self.stateArray[ inpt ] += 1\n return self.wrapped.activate(inpt)\n" ]
[ [ "scipy.zeros" ] ]
zparnold/cs7641
[ "e37e7b9259237adffbeb36ccc8dd17f67892286a" ]
[ "assignment2/nn_function.py" ]
[ "import sys\n\nimport six\n\nsys.modules['sklearn.externals.six'] = six\nimport mlrose_hiive as mlrose\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import accuracy_score\nimport matplotlib.pyplot as plt\nfrom matplotlib.lines import Line2D\n\n\ndef run_something(values, restarts=0, schedule=mlrose.GeomDecay(), mutation_prob=0.1, pop_size=200):\n curves = []\n for x in ['identity', 'relu', 'sigmoid', 'tanh']:\n # Normalize feature data\n if values['algo'] == 'rhc':\n nn_model1 = mlrose.NeuralNetwork(hidden_nodes=[10, 10], activation=x,\n algorithm='random_hill_climb', max_iters=100,\n bias=True, is_classifier=True, learning_rate=0.00001,\n early_stopping=True, max_attempts=100,\n random_state=1, restarts=restarts, curve=True, clip_max=1)\n if values['algo'] == 'sa':\n nn_model1 = mlrose.NeuralNetwork(hidden_nodes=[10, 10], activation=x,\n algorithm='simulated_annealing', max_iters=100,\n bias=True, is_classifier=True, learning_rate=0.00001,\n early_stopping=True, max_attempts=100,\n random_state=1, schedule=schedule, curve=True, clip_max=1)\n if values['algo'] == 'ga':\n nn_model1 = mlrose.NeuralNetwork(hidden_nodes=[10, 10], activation=x,\n algorithm='genetic_alg', max_iters=100,\n bias=True, is_classifier=True, learning_rate=0.00001,\n early_stopping=True, max_attempts=100,\n random_state=1, pop_size=pop_size, mutation_prob=mutation_prob, curve=True,\n clip_max=1)\n print('begin training')\n nn_model1.fit(values[\"X_train\"], values[\"y_train\"])\n # Predict labels for train set and assess accuracy\n y_train_pred = nn_model1.predict(values[\"X_train\"])\n\n y_train_accuracy = accuracy_score(values[\"y_train\"], y_train_pred)\n\n print('Training accuracy: ', y_train_accuracy)\n\n # Predict labels for test set and assess accuracy\n y_test_pred = nn_model1.predict(values[\"X_test\"])\n\n y_test_accuracy = accuracy_score(values[\"y_test\"], y_test_pred)\n\n print('Test accuracy: ', y_test_accuracy)\n\n print('Loss function value', nn_model1.loss)\n curves.append(nn_model1.fitness_curve)\n return curves\n\n\ndef main():\n # ds1 = pd.read_csv('../assignment1/data/adult.data',\n # names=['age', 'workclass', 'fnlwgt', 'education', 'education-num', 'marital-status', 'occupation',\n # 'relationship', 'race', 'sex', 'capital-gain', 'capital-loss', 'hours-per-week',\n # 'native-country', '<=50k'])\n # ds1.dropna()\n # ds1.drop_duplicates()\n # ds1 = ds1[ds1['workclass'] != '?']\n # ds1 = ds1[ds1['occupation'] != '?']\n # ds1 = ds1[ds1['education'] != '?']\n # ds1 = ds1[ds1['marital-status'] != '?']\n # ds1 = ds1[ds1['relationship'] != '?']\n # ds1 = ds1[ds1['race'] != '?']\n # ds1 = ds1[ds1['sex'] != '?']\n # ds1 = ds1[ds1['native-country'] != '?']\n # ds1_dummies = pd.get_dummies(ds1, columns=['workclass', 'education', 'marital-status', 'occupation', 'relationship',\n # 'race', 'sex', 'native-country'])\n # ds1_dummies.dropna()\n # ds1_dummies['<=50k'].value_counts()\n # ds1_dummies['<=50k'] = ds1_dummies['<=50k'].map({'<=50K': 1, '>50K': 0})\n # ds1_labels = ds1_dummies['<=50k']\n # ds1_dummies = ds1_dummies.drop(['<=50k'], axis=1)\n ds2 = pd.read_csv('../assignment1/data/bank-additional-full.csv', delimiter=';')\n ds2.dropna()\n ds2.drop_duplicates()\n ds2_dummies = pd.get_dummies(ds2, columns=['job', 'marital', 'education', 'default', 'housing', 'loan', 'contact',\n 'month', 'day_of_week', 'poutcome'])\n ds2_dummies.dropna()\n ds2_dummies['y'].value_counts()\n ds2_dummies['y'] = ds2_dummies['y'].map({'yes': 1, 'no': 0})\n ds2_labels = ds2_dummies['y']\n ds2_dummies = ds2_dummies.drop(['y'], axis=1)\n scaler = StandardScaler()\n\n scaled_ds1_dummies = scaler.fit_transform(ds2_dummies, y=ds2_labels)\n\n X_train, X_test, y_train, y_test = train_test_split(scaled_ds1_dummies, ds2_labels, test_size=0.20,\n stratify=ds2_labels)\n\n v = {\"X_train\": X_train, \"X_test\": X_test, \"y_train\": y_train, \"y_test\": y_test}\n\n print(\"Random Hill Climbing\")\n v['algo'] = 'rhc'\n rhc = run_something(v, 0)\n print(rhc)\n print(\"SA\")\n\n v['algo'] = 'sa'\n sa = run_something(v, 0, mlrose.ExpDecay(), 0.1)\n print(sa)\n print(\"GA\")\n\n v['algo'] = 'ga'\n ga = run_something(v, 0, mlrose.ExpDecay(), 0.1, 100)\n\n f, axarr = plt.subplots(1, 3)\n f.set_figheight(3)\n f.set_figwidth(9)\n for y, i in zip(rhc, ['r', 'b', 'g', 'y']):\n axarr[0].plot(y, color=i)\n axarr[0].set_title('RHC vs Activation Function')\n for y, i in zip(sa, ['r', 'b', 'g', 'y']):\n axarr[1].plot(y, color=i)\n axarr[1].set_title('SA vs Activation Function')\n for y, i in zip(ga, ['r', 'b', 'g', 'y']):\n axarr[2].plot(y, color=i)\n axarr[2].set_title('GA vs Activation Function')\n # Fine-tune figure; hide x ticks for top plots and y ticks for right plots\n # plt.setp([a.get_xticklabels() for a in axarr[0]], visible=False)\n # plt.setp([a.get_yticklabels() for a in axarr[:, 1]], visible=False)\n plt.legend(handles=[Line2D([0], [0], color='r', lw=4, label='identity'),\n Line2D([0], [0], color='b', lw=4, label='relu'),\n Line2D([0], [0], color='g', lw=4, label='sigmoid'),\n Line2D([0], [0], color='y', lw=4, label='tanh')])\n # plt.title('Input size vs fitness curve One Max')\n # plt.xlabel('Function iteration count')\n # plt.ylabel('Fitness function value')\n\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "matplotlib.lines.Line2D", "sklearn.preprocessing.StandardScaler", "matplotlib.pyplot.subplots", "sklearn.metrics.accuracy_score", "sklearn.model_selection.train_test_split", "matplotlib.pyplot.show", "pandas.read_csv", "pandas.get_dummies" ] ]
chaowentao/mmpose
[ "b528c60ef4fab56d35d1ed7e187023794639be26" ]
[ "mmpose/datasets/datasets/top_down/topdown_mpii_trb_dataset.py" ]
[ "import copy as cp\nimport os\nimport os.path as osp\nfrom collections import OrderedDict\n\nimport json_tricks as json\nimport numpy as np\n\nfrom mmpose.datasets.builder import DATASETS\nfrom .topdown_base_dataset import TopDownBaseDataset\n\n\[email protected]_module()\nclass TopDownMpiiTrbDataset(TopDownBaseDataset):\n \"\"\"MPII-TRB Dataset dataset for top-down pose estimation.\n\n `TRB: A Novel Triplet Representation for Understanding 2D Human Body`\n ICCV'2019 More details can be found in the `paper\n <https://arxiv.org/abs/1910.11535>`__ .\n\n The dataset loads raw features and apply specified transforms\n to return a dict containing the image tensors and other information.\n\n MPII-TRB keypoint indexes::\n\n 0: 'left_shoulder'\n 1: 'right_shoulder'\n 2: 'left_elbow'\n 3: 'right_elbow'\n 4: 'left_wrist'\n 5: 'right_wrist'\n 6: 'left_hip'\n 7: 'right_hip'\n 8: 'left_knee'\n 9: 'right_knee'\n 10: 'left_ankle'\n 11: 'right_ankle'\n 12: 'head'\n 13: 'neck'\n\n 14: 'right_neck'\n 15: 'left_neck'\n 16: 'medial_right_shoulder'\n 17: 'lateral_right_shoulder'\n 18: 'medial_right_bow'\n 19: 'lateral_right_bow'\n 20: 'medial_right_wrist'\n 21: 'lateral_right_wrist'\n 22: 'medial_left_shoulder'\n 23: 'lateral_left_shoulder'\n 24: 'medial_left_bow'\n 25: 'lateral_left_bow'\n 26: 'medial_left_wrist'\n 27: 'lateral_left_wrist'\n 28: 'medial_right_hip'\n 29: 'lateral_right_hip'\n 30: 'medial_right_knee'\n 31: 'lateral_right_knee'\n 32: 'medial_right_ankle'\n 33: 'lateral_right_ankle'\n 34: 'medial_left_hip'\n 35: 'lateral_left_hip'\n 36: 'medial_left_knee'\n 37: 'lateral_left_knee'\n 38: 'medial_left_ankle'\n 39: 'lateral_left_ankle'\n\n Args:\n ann_file (str): Path to the annotation file.\n img_prefix (str): Path to a directory where images are held.\n Default: None.\n data_cfg (dict): config\n pipeline (list[dict | callable]): A sequence of data transforms.\n test_mode (bool): Store True when building test or\n validation dataset. Default: False.\n \"\"\"\n\n def __init__(self,\n ann_file,\n img_prefix,\n data_cfg,\n pipeline,\n test_mode=False):\n\n super().__init__(\n ann_file, img_prefix, data_cfg, pipeline, test_mode=test_mode)\n\n # flip_pairs in MPII-TRB\n self.ann_info['flip_pairs'] = [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9],\n [10, 11], [14, 15], [16, 22], [28, 34],\n [17, 23], [29, 35], [18, 24], [30, 36],\n [19, 25], [31, 37], [20, 26], [32, 38],\n [21, 27], [33, 39]]\n\n self.ann_info['upper_body_ids'] = [0, 1, 2, 3, 4, 5, 12, 13]\n self.ann_info['lower_body_ids'] = [6, 7, 8, 9, 10, 11]\n self.ann_info['upper_body_ids'].extend(list(range(14, 28)))\n self.ann_info['lower_body_ids'].extend(list(range(28, 40)))\n\n self.ann_info['use_different_joint_weights'] = False\n\n assert self.ann_info['num_joints'] == 40\n self.ann_info['joint_weights'] = np.ones(\n (self.ann_info['num_joints'], 1), dtype=np.float32)\n\n self.db = self._get_db(ann_file)\n self.image_set = set(x['image_file'] for x in self.db)\n self.num_images = len(self.image_set)\n\n print(f'=> num_images: {self.num_images}')\n print(f'=> load {len(self.db)} samples')\n\n def _get_db(self, ann_file):\n \"\"\"Load dataset.\"\"\"\n with open(ann_file, 'r') as f:\n data = json.load(f)\n tmpl = dict(\n image_file=None,\n center=None,\n scale=None,\n rotation=0,\n joints_3d=None,\n joints_3d_visible=None,\n dataset='mpii_trb')\n\n imid2info = {\n int(osp.splitext(x['file_name'])[0]): x\n for x in data['images']\n }\n\n num_joints = self.ann_info['num_joints']\n gt_db = []\n\n for anno in data['annotations']:\n newitem = cp.deepcopy(tmpl)\n image_id = anno['image_id']\n newitem['image_file'] = os.path.join(\n self.img_prefix, imid2info[image_id]['file_name'])\n\n if max(anno['keypoints']) == 0:\n continue\n\n joints_3d = np.zeros((num_joints, 3), dtype=np.float32)\n joints_3d_visible = np.zeros((num_joints, 3), dtype=np.float32)\n\n for ipt in range(num_joints):\n joints_3d[ipt, 0] = anno['keypoints'][ipt * 3 + 0]\n joints_3d[ipt, 1] = anno['keypoints'][ipt * 3 + 1]\n joints_3d[ipt, 2] = 0\n t_vis = min(anno['keypoints'][ipt * 3 + 2], 1)\n joints_3d_visible[ipt, :] = (t_vis, t_vis, 0)\n\n center = np.array(anno['center'], dtype=np.float32)\n scale = self.ann_info['image_size'] / anno['scale'] / 200.0\n newitem['center'] = center\n newitem['scale'] = scale\n newitem['joints_3d'] = joints_3d\n newitem['joints_3d_visible'] = joints_3d_visible\n if 'headbox' in anno:\n newitem['headbox'] = anno['headbox']\n gt_db.append(newitem)\n\n return gt_db\n\n def _evaluate_kernel(self, pred, joints_3d, joints_3d_visible, headbox):\n \"\"\"Evaluate one example.\"\"\"\n num_joints = self.ann_info['num_joints']\n headbox = np.array(headbox)\n threshold = np.linalg.norm(headbox[:2] - headbox[2:]) * 0.3\n hit = np.zeros(num_joints, dtype=np.float32)\n exist = np.zeros(num_joints, dtype=np.float32)\n\n for i in range(num_joints):\n pred_pt = pred[i]\n gt_pt = joints_3d[i]\n vis = joints_3d_visible[i][0]\n if vis:\n exist[i] = 1\n else:\n continue\n distance = np.linalg.norm(pred_pt[:2] - gt_pt[:2])\n if distance < threshold:\n hit[i] = 1\n return hit, exist\n\n def evaluate(self, outputs, res_folder, metric='PCKh', **kwargs):\n \"\"\"Evaluate PCKh for MPII-TRB dataset.\n\n Note:\n batch_size: N\n num_keypoints: K\n heatmap height: H\n heatmap width: W\n\n Args:\n outputs(list(preds, boxes, image_path, heatmap)):\n\n * preds(np.ndarray[1,K,3]): The first two dimensions are\n coordinates, score is the third dimension of the array.\n * boxes(np.ndarray[1,6]): [center[0], center[1], scale[0]\n , scale[1],area, score]\n * image_path(list[str]): For example, ['0', '0',\n '0', '0', '0', '1', '1', '6', '3', '.', 'j', 'p', 'g']\n * heatmap (np.ndarray[N, K, H, W]): model output heatmap.\n res_folder(str): Path of directory to save the results.\n metric (str | list[str]): Metrics to be performed.\n Defaults: 'PCKh'.\n\n Returns:\n dict: PCKh for each joint\n \"\"\"\n metrics = metric if isinstance(metric, list) else [metric]\n allowed_metrics = ['PCKh']\n for metric in metrics:\n if metric not in allowed_metrics:\n raise KeyError(f'metric {metric} is not supported')\n\n res_file = os.path.join(res_folder, 'result_keypoints.json')\n\n kpts = []\n\n for preds, boxes, image_path, _ in outputs:\n str_image_path = ''.join(image_path)\n image_id = int(osp.basename(osp.splitext(str_image_path)[0]))\n\n kpts.append({\n 'keypoints': preds[0].tolist(),\n 'center': boxes[0][0:2].tolist(),\n 'scale': boxes[0][2:4].tolist(),\n 'area': float(boxes[0][4]),\n 'score': float(boxes[0][5]),\n 'image_id': image_id,\n })\n\n self._write_keypoint_results(kpts, res_file)\n info_str = self._report_metric(res_file)\n name_value = OrderedDict(info_str)\n\n return name_value\n\n @staticmethod\n def _write_keypoint_results(keypoints, res_file):\n \"\"\"Write results into a json file.\"\"\"\n\n with open(res_file, 'w') as f:\n json.dump(keypoints, f, sort_keys=True, indent=4)\n\n def _report_metric(self, res_file):\n \"\"\"Keypoint evaluation.\n\n Report Mean Acc of skeleton, contour and all joints.\n \"\"\"\n num_joints = self.ann_info['num_joints']\n hit = np.zeros(num_joints, dtype=np.float32)\n exist = np.zeros(num_joints, dtype=np.float32)\n\n with open(res_file, 'r') as fin:\n preds = json.load(fin)\n\n assert len(preds) == len(\n self.db), f'len(preds)={len(preds)}, len(self.db)={len(self.db)}'\n for pred, item in zip(preds, self.db):\n h, e = self._evaluate_kernel(pred['keypoints'], item['joints_3d'],\n item['joints_3d_visible'],\n item['headbox'])\n hit += h\n exist += e\n skeleton = np.sum(hit[:14]) / np.sum(exist[:14])\n contour = np.sum(hit[14:]) / np.sum(exist[14:])\n mean = np.sum(hit) / np.sum(exist)\n\n info_str = []\n info_str.append(('Skeleton_acc', skeleton.item()))\n info_str.append(('Contour_acc', contour.item()))\n info_str.append(('PCKh', mean.item()))\n return info_str\n" ]
[ [ "numpy.array", "numpy.linalg.norm", "numpy.zeros", "numpy.sum", "numpy.ones" ] ]
Immich/jina
[ "1f5f7cf4d82029d76ab41df157526fe6f6e0da50", "1f5f7cf4d82029d76ab41df157526fe6f6e0da50" ]
[ "tests/unit/executors/indexers/test_numpyindexer.py", "tests/unit/executors/indexers/test_numpyindexer_batching.py" ]
[ "import os\n\nimport numpy as np\nimport pytest\n\nfrom jina.executors.indexers import BaseIndexer\nfrom jina.executors.indexers.vector import NumpyIndexer\n\n# fix the seed here\n\nnp.random.seed(500)\nretr_idx = None\nnum_data = 100\nnum_dim = 64\nnum_query = 10\nvec_idx = np.array(np.random.randint(0, high=num_data, size=[num_data]), dtype=(np.str_, 16))\nvec = np.random.random([num_data, num_dim])\nquery = np.array(np.random.random([num_query, num_dim]), dtype=np.float32)\n\n\[email protected]('batch_size, compress_level', [(None, 0), (None, 1), (2, 0), (2, 1)])\ndef test_numpy_indexer(batch_size, compress_level, test_metas):\n with NumpyIndexer(metric='euclidean', index_filename='np.test.gz', compress_level=compress_level,\n metas=test_metas) as indexer:\n indexer.batch_size = batch_size\n indexer.add(vec_idx, vec)\n indexer.save()\n assert os.path.exists(indexer.index_abspath)\n save_abspath = indexer.save_abspath\n\n with BaseIndexer.load(save_abspath) as indexer:\n assert isinstance(indexer, NumpyIndexer)\n if compress_level == 0:\n assert isinstance(indexer.query_handler, np.memmap)\n idx, dist = indexer.query(query, top_k=4)\n assert idx.shape == dist.shape\n assert idx.shape == (num_query, 4)\n\n\ndef test_numpy_indexer_long_ids(test_metas):\n with NumpyIndexer(metric='euclidean', index_filename='np.test.gz', compress_level=0,\n metas=test_metas, key_length=20) as indexer:\n indexer.batch_size = 4\n long_vec_id = np.array(vec_idx, dtype=(np.str_, 20))\n long_vec_id[0] = '1234512345123451234'\n indexer.add(long_vec_id, vec)\n indexer.save()\n assert os.path.exists(indexer.index_abspath)\n save_abspath = indexer.save_abspath\n # assert False\n\n with BaseIndexer.load(save_abspath) as indexer:\n assert isinstance(indexer, NumpyIndexer)\n idx, dist = indexer.query(query, top_k=4)\n assert idx.shape == dist.shape\n assert idx.shape == (num_query, 4)\n\n\[email protected]('batch_size, compress_level', [(None, 0), (None, 1), (16, 0), (16, 1)])\ndef test_numpy_indexer_known(batch_size, compress_level, test_metas):\n vectors = np.array([[1, 1, 1],\n [10, 10, 10],\n [100, 100, 100],\n [1000, 1000, 1000]])\n keys = np.array(['4', '5', '6', '7'], dtype=(np.str_, 16))\n with NumpyIndexer(metric='euclidean', index_filename='np.test.gz', compress_level=compress_level,\n metas=test_metas) as indexer:\n indexer.batch_size = batch_size\n indexer.add(keys, vectors)\n indexer.save()\n assert os.path.exists(indexer.index_abspath)\n save_abspath = indexer.save_abspath\n\n queries = np.array([[1, 1, 1],\n [10, 10, 10],\n [100, 100, 100],\n [1000, 1000, 1000]])\n with BaseIndexer.load(save_abspath) as indexer:\n assert isinstance(indexer, NumpyIndexer)\n if compress_level == 0:\n assert isinstance(indexer.query_handler, np.memmap)\n idx, dist = indexer.query(queries, top_k=2)\n np.testing.assert_equal(idx, np.array([['4', '5'], ['5', '4'], ['6', '5'], ['7', '6']]))\n assert idx.shape == dist.shape\n assert idx.shape == (4, 2)\n np.testing.assert_equal(indexer.query_by_key(['7', '4']), vectors[[3, 0]])\n\n\[email protected]('batch_size, compress_level', [(None, 0), (None, 1), (16, 0), (16, 1)])\ndef test_scipy_indexer(batch_size, compress_level, test_metas):\n with NumpyIndexer(metric='euclidean', index_filename='np.test.gz', backend='scipy', compress_level=compress_level,\n metas=test_metas) as indexer:\n indexer.batch_size = batch_size\n indexer.add(vec_idx, vec)\n indexer.save()\n assert os.path.exists(indexer.index_abspath)\n save_abspath = indexer.save_abspath\n\n with BaseIndexer.load(save_abspath) as indexer:\n assert isinstance(indexer, NumpyIndexer)\n if compress_level == 0:\n assert isinstance(indexer.query_handler, np.memmap)\n idx, dist = indexer.query(query, top_k=4)\n assert idx.shape == dist.shape\n assert idx.shape == (num_query, 4)\n\n\[email protected]('batch_size, compress_level', [(None, 0), (None, 1), (16, 0), (16, 1)])\ndef test_numpy_indexer_known_big(batch_size, compress_level, test_metas):\n \"\"\"Let's try to have some real test. We will have an index with 10k vectors of random values between 5 and 10.\n We will change tweak some specific vectors that we expect to be retrieved at query time. We will tweak vector\n at index [0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000], this will also be the query vectors.\n Then the keys will be assigned shifted to test the proper usage of `int2ext_id` and `ext2int_id`\n \"\"\"\n vectors = np.random.uniform(low=5.0, high=10.0, size=(10000, 1024))\n\n queries = np.empty((10, 1024))\n for idx in range(0, 10000, 1000):\n array = idx * np.ones((1, 1024))\n queries[int(idx / 1000)] = array\n vectors[idx] = array\n\n keys = np.array(np.arange(10000, 20000).reshape(-1, 1), dtype=(np.str_, 16))\n\n with NumpyIndexer(metric='euclidean', index_filename='np.test.gz', compress_level=compress_level,\n metas=test_metas) as indexer:\n indexer.add(keys, vectors)\n indexer.save()\n assert os.path.exists(indexer.index_abspath)\n save_abspath = indexer.save_abspath\n\n with BaseIndexer.load(save_abspath) as indexer:\n assert isinstance(indexer, NumpyIndexer)\n if compress_level == 0:\n assert isinstance(indexer.query_handler, np.memmap)\n idx, dist = indexer.query(queries, top_k=1)\n np.testing.assert_equal(idx, np.array(\n [['10000'], ['11000'], ['12000'], ['13000'], ['14000'], ['15000'], ['16000'], ['17000'], ['18000'], ['19000']]))\n assert idx.shape == dist.shape\n assert idx.shape == (10, 1)\n np.testing.assert_equal(indexer.query_by_key(['10000', '15000']), vectors[[0, 5000]])\n\n\[email protected]('compress_level', [0, 1, 2, 3, 4, 5])\ndef test_scipy_indexer_known_big(compress_level, test_metas):\n \"\"\"Let's try to have some real test. We will have an index with 10k vectors of random values between 5 and 10.\n We will change tweak some specific vectors that we expect to be retrieved at query time. We will tweak vector\n at index [0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000], this will also be the query vectors.\n Then the keys will be assigned shifted to test the proper usage of `int2ext_id` and `ext2int_id`\n \"\"\"\n vectors = np.random.uniform(low=5.0, high=10.0, size=(10000, 1024))\n\n queries = np.empty((10, 1024))\n for idx in range(0, 10000, 1000):\n array = idx * np.ones((1, 1024))\n queries[int(idx / 1000)] = array\n vectors[idx] = array\n\n keys = np.array(np.arange(10000, 20000).reshape(-1, 1), dtype=(np.str_, 16))\n\n with NumpyIndexer(metric='euclidean', index_filename='np.test.gz', backend='scipy', compress_level=compress_level,\n metas=test_metas) as indexer:\n indexer.add(keys, vectors)\n indexer.save()\n assert os.path.exists(indexer.index_abspath)\n save_abspath = indexer.save_abspath\n\n with BaseIndexer.load(save_abspath) as indexer:\n assert isinstance(indexer, NumpyIndexer)\n if compress_level == 0:\n assert isinstance(indexer.query_handler, np.memmap)\n idx, dist = indexer.query(queries, top_k=1)\n np.testing.assert_equal(idx, np.array(\n [['10000'], ['11000'], ['12000'], ['13000'], ['14000'], ['15000'], ['16000'], ['17000'], ['18000'], ['19000']]))\n assert idx.shape == dist.shape\n assert idx.shape == (10, 1)\n np.testing.assert_equal(indexer.query_by_key(['10000', '15000']), vectors[[0, 5000]])\n\n\[email protected]('batch_size, num_docs, top_k',\n [(1, 10, 1), (1, 10, 10), (10, 1, 1), (10, 1000, 10), (10, 10, 100)])\ndef test__get_sorted_top_k(batch_size, num_docs, top_k, test_metas):\n dist = np.random.uniform(size=(batch_size, num_docs))\n\n expected_idx = np.argsort(dist)[:, :top_k]\n expected_dist = np.sort(dist)[:, :top_k]\n\n with NumpyIndexer(metric='euclidean', metas=test_metas) as indexer:\n idx, dist = indexer._get_sorted_top_k(dist, top_k=top_k)\n\n np.testing.assert_equal(idx, expected_idx)\n np.testing.assert_equal(dist, expected_dist)\n\n\[email protected]('batch_size, compress_level', [(None, 0), (None, 1), (2, 0), (2, 1)])\ndef test_numpy_indexer_empty_data(batch_size, compress_level, test_metas):\n idx_file_path = os.path.join(test_metas['workspace'], 'np.test.gz')\n with NumpyIndexer(index_filename=str(idx_file_path), compress_level=compress_level, metas=test_metas) as indexer:\n indexer.batch_size = batch_size\n indexer.touch()\n indexer.save()\n assert os.path.exists(indexer.index_abspath)\n save_abspath = indexer.save_abspath\n\n with BaseIndexer.load(save_abspath) as indexer:\n assert isinstance(indexer, NumpyIndexer)\n idx, dist = indexer.query(query, top_k=4)\n assert idx is None\n assert dist is None\n\n\[email protected]('metric', ['euclidean', 'cosine'])\ndef test_indexer_one_dimensional(metric, test_metas):\n import math\n add_vec_idx = np.array(['0'], dtype=(np.str_, 16))\n add_vec = np.asarray([[1]])\n query_vec = np.asarray([[2]])\n with NumpyIndexer(metric=metric, index_filename='np.test.gz',\n metas=test_metas) as indexer:\n indexer.add(add_vec_idx, add_vec)\n\n indexer.save()\n assert os.path.exists(indexer.index_abspath)\n save_abspath = indexer.save_abspath\n\n with BaseIndexer.load(save_abspath) as indexer:\n assert isinstance(indexer, NumpyIndexer)\n assert isinstance(indexer.query_handler, np.memmap)\n idx, dist = indexer.query(query_vec, top_k=4)\n assert idx.shape == dist.shape\n assert idx.shape == (1, 1)\n assert not math.isnan(dist[0])\n\n\[email protected]('dimension', [1, 64])\[email protected]('metric', ['euclidean', 'cosine'])\ndef test_indexer_zeros(metric, dimension, test_metas):\n import math\n query_vec = np.array(np.zeros([1, dimension]), dtype=np.float32)\n add_vec_idx = np.array(np.random.randint(0, high=num_data, size=[num_data]), dtype=(np.str_, 16))\n add_vec = np.random.random([num_data, dimension])\n with NumpyIndexer(metric=metric, index_filename='np.test.gz',\n metas=test_metas) as indexer:\n indexer.add(add_vec_idx, add_vec)\n indexer.save()\n assert os.path.exists(indexer.index_abspath)\n save_abspath = indexer.save_abspath\n\n with BaseIndexer.load(save_abspath) as indexer:\n assert isinstance(indexer, NumpyIndexer)\n assert isinstance(indexer.query_handler, np.memmap)\n idx, dist = indexer.query(query_vec, top_k=4)\n\n assert idx.shape == dist.shape\n assert idx.shape == (1, 4)\n if metric == 'cosine':\n assert all(math.isnan(x) for x in dist[0])\n else:\n assert not any(math.isnan(x) for x in dist[0])\n\n\[email protected]('compress_level', [0, 1, 2, 3, 4, 5])\ndef test_numpy_update_delete(compress_level, test_metas):\n np.random.seed(500)\n num_dim = 3\n vec_idx = np.array(['12', '112', '903'], dtype=(np.str_, 16))\n vec = np.random.random([len(vec_idx), num_dim])\n\n with NumpyIndexer(metric='euclidean', index_filename='np.test.gz', compress_level=compress_level,\n metas=test_metas) as indexer:\n indexer.add(vec_idx, vec)\n indexer.save()\n assert indexer.num_dim == num_dim\n assert indexer.size == len(vec_idx)\n assert os.path.exists(indexer.index_abspath)\n save_abspath = indexer.save_abspath\n\n with BaseIndexer.load(save_abspath) as indexer:\n assert isinstance(indexer, NumpyIndexer)\n query_results = indexer.query_by_key(vec_idx)\n assert np.array_equal(vec, query_results)\n\n # update\n key_to_update = vec_idx[0]\n data_to_update = np.random.random([1, num_dim])\n # nonexistent key\n random_keys = np.array(['999'], dtype=(np.str_, 16))\n random_data = np.random.random([1, num_dim])\n\n with BaseIndexer.load(save_abspath) as indexer:\n assert isinstance(indexer, NumpyIndexer)\n # NON-EXISTENT KEYS: this will log warning but not fail\n indexer.update(random_keys, random_data)\n indexer.update([key_to_update], data_to_update)\n indexer.save()\n\n with BaseIndexer.load(save_abspath) as indexer:\n assert isinstance(indexer, NumpyIndexer)\n query_results = indexer.query_by_key([key_to_update])\n assert np.array_equal(data_to_update, query_results)\n\n # delete\n keys_to_delete = 1\n vec_idx_to_delete = vec_idx[:keys_to_delete]\n\n with BaseIndexer.load(save_abspath) as indexer:\n assert isinstance(indexer, NumpyIndexer)\n indexer.delete(vec_idx_to_delete)\n indexer.save()\n assert indexer.size == len(vec_idx) - keys_to_delete\n\n assert indexer.size == len(vec_idx) - keys_to_delete\n\n with BaseIndexer.load(save_abspath) as indexer:\n assert isinstance(indexer, NumpyIndexer)\n assert indexer.size == len(vec_idx) - keys_to_delete\n # random non-existent key\n assert indexer.query_by_key(['123861942']) is None\n query_results = indexer.query_by_key(vec_idx[keys_to_delete:])\n expected = vec[keys_to_delete:]\n np.testing.assert_allclose(query_results, expected, equal_nan=True)\n\n\[email protected]('batch_size, compress_level', [(None, 0), (None, 1), (16, 0), (16, 1)])\ndef test_numpy_indexer_known_and_delete(batch_size, compress_level, test_metas):\n vectors = np.array([[1, 1, 1],\n [10, 10, 10],\n [100, 100, 100]])\n keys = np.array(['4', '5', '6'], dtype=(np.str_, 16))\n with NumpyIndexer(metric='euclidean', index_filename='np.test.gz', compress_level=compress_level,\n metas=test_metas) as indexer:\n indexer.batch_size = batch_size\n indexer.add(keys, vectors)\n indexer.save()\n assert os.path.exists(indexer.index_abspath)\n save_abspath = indexer.save_abspath\n\n top_k = 3\n queries = np.array([[1, 1, 1],\n [10, 10, 10]])\n with BaseIndexer.load(save_abspath) as indexer:\n assert isinstance(indexer, NumpyIndexer)\n idx, dist = indexer.query(queries, top_k=top_k)\n np.testing.assert_equal(idx, np.array([['4', '5', '6'], ['5', '4', '6']]))\n assert idx.shape == dist.shape\n assert idx.shape == (len(queries), top_k)\n np.testing.assert_equal(indexer.query_by_key(['5', '4', '6']), vectors[[1, 0, 2]])\n\n # update and query again\n key_to_update = np.array(['4'])\n data_to_update = np.array([[1000, 1000, 1000]])\n\n with BaseIndexer.load(save_abspath) as indexer:\n assert isinstance(indexer, NumpyIndexer)\n indexer.update(key_to_update, data_to_update)\n indexer.save()\n\n with BaseIndexer.load(save_abspath) as indexer:\n assert isinstance(indexer, NumpyIndexer)\n idx, dist = indexer.query(queries, top_k=top_k)\n np.testing.assert_equal(idx, np.array([['5', '6', '4'], ['5', '6', '4']]))\n assert idx.shape == dist.shape\n assert idx.shape == (len(queries), top_k)\n\n # delete and query again\n with BaseIndexer.load(save_abspath) as indexer:\n assert isinstance(indexer, NumpyIndexer)\n indexer.delete([4])\n indexer.save()\n\n top_k = 2\n queries = np.array([[100, 100, 100],\n [10, 10, 10]])\n with BaseIndexer.load(save_abspath) as indexer:\n assert isinstance(indexer, NumpyIndexer)\n idx, dist = indexer.query(queries, top_k=2)\n np.testing.assert_equal(idx, np.array([['6', '5'], ['5', '6']]))\n assert idx.shape == dist.shape\n assert idx.shape == (len(queries), top_k)\n np.testing.assert_equal(indexer.query_by_key(['6', '5']), vectors[[2, 1]])\n\n # test query by nonexistent key\n with BaseIndexer.load(save_abspath) as indexer:\n assert isinstance(indexer, NumpyIndexer)\n assert indexer.query_by_key(['91237124']) is None\n\n\[email protected]('compress_level', [0, 1, 2, 3])\ndef test_numpy_indexer_with_ref_indexer(compress_level, test_metas):\n vectors = np.array([[1, 1, 1],\n [10, 10, 10],\n [100, 100, 100],\n [1000, 1000, 1000]])\n keys = np.array(['4', '5', '6', '7'], dtype=(np.str_, 16))\n with NumpyIndexer(metric='euclidean', index_filename='np.test.gz', compress_level=compress_level,\n metas=test_metas) as indexer:\n indexer.add(keys, vectors)\n indexer.save()\n assert os.path.exists(indexer.index_abspath)\n index_filename = indexer.index_filename\n\n queries = np.array([[1, 1, 1],\n [10, 10, 10],\n [100, 100, 100],\n [1000, 1000, 1000]])\n with NumpyIndexer(metric='euclidean', ref_indexer=indexer, metas=test_metas) as new_indexer:\n assert new_indexer.compress_level == compress_level\n assert new_indexer.index_filename == index_filename\n assert isinstance(indexer, NumpyIndexer)\n if compress_level == 0:\n assert isinstance(new_indexer.query_handler, np.memmap)\n idx, dist = new_indexer.query(queries, top_k=2)\n np.testing.assert_equal(idx, np.array([['4', '5'], ['5', '4'], ['6', '5'], ['7', '6']]))\n assert idx.shape == dist.shape\n assert idx.shape == (4, 2)\n np.testing.assert_equal(new_indexer.query_by_key(['7', '4']), vectors[[3, 0]])\n", "import os\n\nimport pytest\nimport numpy as np\n\nfrom jina.executors.decorators import batching\nfrom jina.executors.indexers import BaseIndexer\nfrom jina.executors.indexers.vector import NumpyIndexer, _ext_B, _euclidean\n\n\nclass MockNumpyIndexer(NumpyIndexer):\n\n @batching(merge_over_axis=1, slice_on=2)\n def _euclidean(self, cached_A, raw_B):\n assert raw_B.shape[0] == self.batch_size\n data = _ext_B(raw_B)\n return _euclidean(cached_A, data)\n\n\[email protected]('batch_size', [2, 5, 10, 20, 100, 500])\ndef test_numpy_indexer_known_big_batch(batch_size, test_metas):\n \"\"\"Let's try to have some real test. We will have an index with 10k vectors of random values between 5 and 10.\n We will change tweak some specific vectors that we expect to be retrieved at query time. We will tweak vector\n at index [0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000], this will also be the query vectors.\n Then the keys will be assigned shifted to test the proper usage of `int2ext_id` and `ext2int_id`\n \"\"\"\n vectors = np.random.uniform(low=5.0, high=10.0, size=(10000, 1024))\n\n queries = np.empty((10, 1024))\n for idx in range(0, 10000, 1000):\n array = idx * np.ones((1, 1024))\n queries[int(idx / 1000)] = array\n vectors[idx] = array\n\n keys = np.array(np.arange(10000, 20000).reshape(-1, 1), dtype=(np.str_, 16))\n\n with MockNumpyIndexer(metric='euclidean', index_filename='np.test.gz', compress_level=0,\n metas=test_metas) as indexer:\n indexer.batch_size = batch_size\n indexer.add(keys, vectors)\n indexer.save()\n assert os.path.exists(indexer.index_abspath)\n save_abspath = indexer.save_abspath\n\n with BaseIndexer.load(save_abspath) as indexer:\n indexer.batch_size = batch_size\n assert isinstance(indexer, MockNumpyIndexer)\n assert isinstance(indexer._raw_ndarray, np.memmap)\n idx, dist = indexer.query(queries, top_k=1)\n np.testing.assert_equal(idx, np.array(\n [['10000'], ['11000'], ['12000'], ['13000'], ['14000'], ['15000'], ['16000'], ['17000'], ['18000'], ['19000']]))\n assert idx.shape == dist.shape\n assert idx.shape == (10, 1)\n np.testing.assert_equal(indexer.query_by_key(['10000', '15000']), vectors[[0, 5000]])\n" ]
[ [ "numpy.testing.assert_allclose", "numpy.array", "numpy.empty", "numpy.asarray", "numpy.zeros", "numpy.testing.assert_equal", "numpy.random.seed", "numpy.array_equal", "numpy.ones", "numpy.random.uniform", "numpy.random.randint", "numpy.sort", "numpy.argsort", "numpy.arange", "numpy.random.random" ], [ "numpy.array", "numpy.empty", "numpy.ones", "numpy.random.uniform", "numpy.arange" ] ]
yarikoptic/scipy
[ "f0ebf744dea44c14f298311b8930cd8f55ae9f96" ]
[ "scipy/signal/ltisys.py" ]
[ "\"\"\"\nltisys -- a collection of classes and functions for modeling linear\ntime invariant systems.\n\"\"\"\nfrom __future__ import division, print_function, absolute_import\n\n#\n# Author: Travis Oliphant 2001\n#\n# Feb 2010: Warren Weckesser\n# Rewrote lsim2 and added impulse2.\n# Aug 2013: Juan Luis Cano\n# Rewrote abcd_normalize.\n#\n\nfrom .filter_design import tf2zpk, zpk2tf, normalize, freqs\nimport numpy\nfrom numpy import product, zeros, array, dot, transpose, ones, \\\n nan_to_num, zeros_like, linspace\nimport scipy.interpolate as interpolate\nimport scipy.integrate as integrate\nimport scipy.linalg as linalg\nfrom scipy.lib.six import xrange\nfrom numpy import r_, eye, real, atleast_1d, atleast_2d, poly, \\\n squeeze, diag, asarray\n\n__all__ = ['tf2ss', 'ss2tf', 'abcd_normalize', 'zpk2ss', 'ss2zpk', 'lti',\n 'lsim', 'lsim2', 'impulse', 'impulse2', 'step', 'step2', 'bode',\n 'freqresp']\n\n\ndef tf2ss(num, den):\n \"\"\"Transfer function to state-space representation.\n\n Parameters\n ----------\n num, den : array_like\n Sequences representing the numerator and denominator polynomials.\n The denominator needs to be at least as long as the numerator.\n\n Returns\n -------\n A, B, C, D : ndarray\n State space representation of the system.\n\n \"\"\"\n # Controller canonical state-space representation.\n # if M+1 = len(num) and K+1 = len(den) then we must have M <= K\n # states are found by asserting that X(s) = U(s) / D(s)\n # then Y(s) = N(s) * X(s)\n #\n # A, B, C, and D follow quite naturally.\n #\n num, den = normalize(num, den) # Strips zeros, checks arrays\n nn = len(num.shape)\n if nn == 1:\n num = asarray([num], num.dtype)\n M = num.shape[1]\n K = len(den)\n if M > K:\n msg = \"Improper transfer function. `num` is longer than `den`.\"\n raise ValueError(msg)\n if M == 0 or K == 0: # Null system\n return array([], float), array([], float), array([], float), \\\n array([], float)\n\n # pad numerator to have same number of columns has denominator\n num = r_['-1', zeros((num.shape[0], K - M), num.dtype), num]\n\n if num.shape[-1] > 0:\n D = num[:, 0]\n else:\n D = array([], float)\n\n if K == 1:\n return array([], float), array([], float), array([], float), D\n\n frow = -array([den[1:]])\n A = r_[frow, eye(K - 2, K - 1)]\n B = eye(K - 1, 1)\n C = num[:, 1:] - num[:, 0] * den[1:]\n return A, B, C, D\n\n\ndef _none_to_empty_2d(arg):\n if arg is None:\n return zeros((0, 0))\n else:\n return arg\n\n\ndef _atleast_2d_or_none(arg):\n if arg is not None:\n return atleast_2d(arg)\n\n\ndef _shape_or_none(M):\n if M is not None:\n return M.shape\n else:\n return (None,) * 2\n\n\ndef _choice_not_none(*args):\n for arg in args:\n if arg is not None:\n return arg\n\n\ndef _restore(M, shape):\n if M.shape == (0, 0):\n return zeros(shape)\n else:\n if M.shape != shape:\n raise ValueError(\"The input arrays have incompatible shapes.\")\n return M\n\n\ndef abcd_normalize(A=None, B=None, C=None, D=None):\n \"\"\"Check state-space matrices and ensure they are rank-2.\n\n If enough information on the system is provided, that is, enough\n properly-shaped arrays are passed to the function, the missing ones\n are built from this information, ensuring the correct number of\n rows and columns. Otherwise a ValueError is raised.\n\n Parameters\n ----------\n A, B, C, D : array_like, optional\n State-space matrices. All of them are None (missing) by default.\n\n Returns\n -------\n A, B, C, D : array\n Properly shaped state-space matrices.\n\n Raises\n ------\n ValueError\n If not enough information on the system was provided.\n\n \"\"\"\n A, B, C, D = map(_atleast_2d_or_none, (A, B, C, D))\n\n MA, NA = _shape_or_none(A)\n MB, NB = _shape_or_none(B)\n MC, NC = _shape_or_none(C)\n MD, ND = _shape_or_none(D)\n\n p = _choice_not_none(MA, MB, NC)\n q = _choice_not_none(NB, ND)\n r = _choice_not_none(MC, MD)\n if p is None or q is None or r is None:\n raise ValueError(\"Not enough information on the system.\")\n\n A, B, C, D = map(_none_to_empty_2d, (A, B, C, D))\n A = _restore(A, (p, p))\n B = _restore(B, (p, q))\n C = _restore(C, (r, p))\n D = _restore(D, (r, q))\n\n return A, B, C, D\n\n\ndef ss2tf(A, B, C, D, input=0):\n \"\"\"State-space to transfer function.\n\n Parameters\n ----------\n A, B, C, D : ndarray\n State-space representation of linear system.\n input : int, optional\n For multiple-input systems, the input to use.\n\n Returns\n -------\n num, den : 1D ndarray\n Numerator and denominator polynomials (as sequences)\n respectively.\n\n \"\"\"\n # transfer function is C (sI - A)**(-1) B + D\n A, B, C, D = map(asarray, (A, B, C, D))\n # Check consistency and\n # make them all rank-2 arrays\n A, B, C, D = abcd_normalize(A, B, C, D)\n\n nout, nin = D.shape\n if input >= nin:\n raise ValueError(\"System does not have the input specified.\")\n\n # make MOSI from possibly MOMI system.\n if B.shape[-1] != 0:\n B = B[:, input]\n B.shape = (B.shape[0], 1)\n if D.shape[-1] != 0:\n D = D[:, input]\n\n try:\n den = poly(A)\n except ValueError:\n den = 1\n\n if (product(B.shape, axis=0) == 0) and (product(C.shape, axis=0) == 0):\n num = numpy.ravel(D)\n if (product(D.shape, axis=0) == 0) and (product(A.shape, axis=0) == 0):\n den = []\n return num, den\n\n num_states = A.shape[0]\n type_test = A[:, 0] + B[:, 0] + C[0, :] + D\n num = numpy.zeros((nout, num_states + 1), type_test.dtype)\n for k in range(nout):\n Ck = atleast_2d(C[k, :])\n num[k] = poly(A - dot(B, Ck)) + (D[k] - 1) * den\n\n return num, den\n\n\ndef zpk2ss(z, p, k):\n \"\"\"Zero-pole-gain representation to state-space representation\n\n Parameters\n ----------\n z, p : sequence\n Zeros and poles.\n k : float\n System gain.\n\n Returns\n -------\n A, B, C, D : ndarray\n State-space matrices.\n\n \"\"\"\n return tf2ss(*zpk2tf(z, p, k))\n\n\ndef ss2zpk(A, B, C, D, input=0):\n \"\"\"State-space representation to zero-pole-gain representation.\n\n Parameters\n ----------\n A, B, C, D : ndarray\n State-space representation of linear system.\n input : int, optional\n For multiple-input systems, the input to use.\n\n Returns\n -------\n z, p : sequence\n Zeros and poles.\n k : float\n System gain.\n\n \"\"\"\n return tf2zpk(*ss2tf(A, B, C, D, input=input))\n\n\nclass lti(object):\n \"\"\"Linear Time Invariant class which simplifies representation.\n\n Parameters\n ----------\n args : arguments\n The `lti` class can be instantiated with either 2, 3 or 4 arguments.\n The following gives the number of elements in the tuple and the\n interpretation:\n\n * 2: (numerator, denominator)\n * 3: (zeros, poles, gain)\n * 4: (A, B, C, D)\n\n Each argument can be an array or sequence.\n\n Notes\n -----\n `lti` instances have all types of representations available; for example\n after creating an instance s with ``(zeros, poles, gain)`` the transfer\n function representation (numerator, denominator) can be accessed as\n ``s.num`` and ``s.den``.\n\n \"\"\"\n def __init__(self, *args, **kwords):\n \"\"\"\n Initialize the LTI system using either:\n\n - (numerator, denominator)\n - (zeros, poles, gain)\n - (A, B, C, D) : state-space.\n\n \"\"\"\n N = len(args)\n if N == 2: # Numerator denominator transfer function input\n self._num, self._den = normalize(*args)\n self._update(N)\n self.inputs = 1\n if len(self.num.shape) > 1:\n self.outputs = self.num.shape[0]\n else:\n self.outputs = 1\n elif N == 3: # Zero-pole-gain form\n self._zeros, self._poles, self._gain = args\n self._update(N)\n # make sure we have numpy arrays\n self.zeros = numpy.asarray(self.zeros)\n self.poles = numpy.asarray(self.poles)\n self.inputs = 1\n if len(self.zeros.shape) > 1:\n self.outputs = self.zeros.shape[0]\n else:\n self.outputs = 1\n elif N == 4: # State-space form\n self._A, self._B, self._C, self._D = abcd_normalize(*args)\n self._update(N)\n self.inputs = self.B.shape[-1]\n self.outputs = self.C.shape[0]\n else:\n raise ValueError(\"Needs 2, 3, or 4 arguments.\")\n\n def __repr__(self):\n \"\"\"\n Canonical representation using state-space to preserve numerical\n precision and any MIMO information\n \"\"\"\n return '{0}(\\n{1},\\n{2},\\n{3},\\n{4}\\n)'.format(\n self.__class__.__name__,\n repr(self.A),\n repr(self.B),\n repr(self.C),\n repr(self.D),\n )\n\n @property\n def num(self):\n return self._num\n\n @num.setter\n def num(self, value):\n self._num = value\n self._update(2)\n\n @property\n def den(self):\n return self._den\n\n @den.setter\n def den(self, value):\n self._den = value\n self._update(2)\n\n @property\n def zeros(self):\n return self._zeros\n\n @zeros.setter\n def zeros(self, value):\n self._zeros = value\n self._update(3)\n\n @property\n def poles(self):\n return self._poles\n\n @poles.setter\n def poles(self, value):\n self._poles = value\n self._update(3)\n\n @property\n def gain(self):\n return self._gain\n\n @gain.setter\n def gain(self, value):\n self._gain = value\n self._update(3)\n\n @property\n def A(self):\n return self._A\n\n @A.setter\n def A(self, value):\n self._A = value\n self._update(4)\n\n @property\n def B(self):\n return self._B\n\n @B.setter\n def B(self, value):\n self._B = value\n self._update(4)\n\n @property\n def C(self):\n return self._C\n\n @C.setter\n def C(self, value):\n self._C = value\n self._update(4)\n\n @property\n def D(self):\n return self._D\n\n @D.setter\n def D(self, value):\n self._D = value\n self._update(4)\n\n def _update(self, N):\n if N == 2:\n self._zeros, self._poles, self._gain = tf2zpk(self.num, self.den)\n self._A, self._B, self._C, self._D = tf2ss(self.num, self.den)\n if N == 3:\n self._num, self._den = zpk2tf(self.zeros, self.poles, self.gain)\n self._A, self._B, self._C, self._D = zpk2ss(self.zeros,\n self.poles, self.gain)\n if N == 4:\n self._num, self._den = ss2tf(self.A, self.B, self.C, self.D)\n self._zeros, self._poles, self._gain = ss2zpk(self.A, self.B,\n self.C, self.D)\n\n def impulse(self, X0=None, T=None, N=None):\n return impulse(self, X0=X0, T=T, N=N)\n\n def step(self, X0=None, T=None, N=None):\n return step(self, X0=X0, T=T, N=N)\n\n def output(self, U, T, X0=None):\n return lsim(self, U, T, X0=X0)\n\n def bode(self, w=None, n=100):\n \"\"\"\n Calculate Bode magnitude and phase data.\n\n Returns a 3-tuple containing arrays of frequencies [rad/s], magnitude\n [dB] and phase [deg]. See scipy.signal.bode for details.\n\n .. versionadded:: 0.11.0\n\n Examples\n --------\n >>> from scipy import signal\n >>> import matplotlib.pyplot as plt\n\n >>> s1 = signal.lti([1], [1, 1])\n >>> w, mag, phase = s1.bode()\n\n >>> plt.figure()\n >>> plt.semilogx(w, mag) # Bode magnitude plot\n >>> plt.figure()\n >>> plt.semilogx(w, phase) # Bode phase plot\n >>> plt.show()\n\n \"\"\"\n return bode(self, w=w, n=n)\n\n def freqresp(self, w=None, n=10000):\n \"\"\"Calculate the frequency response of a continuous-time system.\n\n Returns a 2-tuple containing arrays of frequencies [rad/s] and\n complex magnitude.\n See scipy.signal.freqresp for details.\n\n \"\"\"\n return freqresp(self, w=w, n=n)\n\n\ndef lsim2(system, U=None, T=None, X0=None, **kwargs):\n \"\"\"\n Simulate output of a continuous-time linear system, by using\n the ODE solver `scipy.integrate.odeint`.\n\n Parameters\n ----------\n system : an instance of the LTI class or a tuple describing the system.\n The following gives the number of elements in the tuple and\n the interpretation:\n\n * 2: (num, den)\n * 3: (zeros, poles, gain)\n * 4: (A, B, C, D)\n\n U : array_like (1D or 2D), optional\n An input array describing the input at each time T. Linear\n interpolation is used between given times. If there are\n multiple inputs, then each column of the rank-2 array\n represents an input. If U is not given, the input is assumed\n to be zero.\n T : array_like (1D or 2D), optional\n The time steps at which the input is defined and at which the\n output is desired. The default is 101 evenly spaced points on\n the interval [0,10.0].\n X0 : array_like (1D), optional\n The initial condition of the state vector. If `X0` is not\n given, the initial conditions are assumed to be 0.\n kwargs : dict\n Additional keyword arguments are passed on to the function\n `odeint`. See the notes below for more details.\n\n Returns\n -------\n T : 1D ndarray\n The time values for the output.\n yout : ndarray\n The response of the system.\n xout : ndarray\n The time-evolution of the state-vector.\n\n Notes\n -----\n This function uses `scipy.integrate.odeint` to solve the\n system's differential equations. Additional keyword arguments\n given to `lsim2` are passed on to `odeint`. See the documentation\n for `scipy.integrate.odeint` for the full list of arguments.\n\n \"\"\"\n if isinstance(system, lti):\n sys = system\n else:\n sys = lti(*system)\n\n if X0 is None:\n X0 = zeros(sys.B.shape[0], sys.A.dtype)\n\n if T is None:\n # XXX T should really be a required argument, but U was\n # changed from a required positional argument to a keyword,\n # and T is after U in the argument list. So we either: change\n # the API and move T in front of U; check here for T being\n # None and raise an exception; or assign a default value to T\n # here. This code implements the latter.\n T = linspace(0, 10.0, 101)\n\n T = atleast_1d(T)\n if len(T.shape) != 1:\n raise ValueError(\"T must be a rank-1 array.\")\n\n if U is not None:\n U = atleast_1d(U)\n if len(U.shape) == 1:\n U = U.reshape(-1, 1)\n sU = U.shape\n if sU[0] != len(T):\n raise ValueError(\"U must have the same number of rows \"\n \"as elements in T.\")\n\n if sU[1] != sys.inputs:\n raise ValueError(\"The number of inputs in U (%d) is not \"\n \"compatible with the number of system \"\n \"inputs (%d)\" % (sU[1], sys.inputs))\n # Create a callable that uses linear interpolation to\n # calculate the input at any time.\n ufunc = interpolate.interp1d(T, U, kind='linear',\n axis=0, bounds_error=False)\n\n def fprime(x, t, sys, ufunc):\n \"\"\"The vector field of the linear system.\"\"\"\n return dot(sys.A, x) + squeeze(dot(sys.B, nan_to_num(ufunc([t]))))\n xout = integrate.odeint(fprime, X0, T, args=(sys, ufunc), **kwargs)\n yout = dot(sys.C, transpose(xout)) + dot(sys.D, transpose(U))\n else:\n def fprime(x, t, sys):\n \"\"\"The vector field of the linear system.\"\"\"\n return dot(sys.A, x)\n xout = integrate.odeint(fprime, X0, T, args=(sys,), **kwargs)\n yout = dot(sys.C, transpose(xout))\n\n return T, squeeze(transpose(yout)), xout\n\n\ndef _cast_to_array_dtype(in1, in2):\n \"\"\"Cast array to dtype of other array, while avoiding ComplexWarning.\n\n Those can be raised when casting complex to real.\n \"\"\"\n if numpy.issubdtype(in2.dtype, numpy.float):\n # dtype to cast to is not complex, so use .real\n in1 = in1.real.astype(in2.dtype)\n else:\n in1 = in1.astype(in2.dtype)\n\n return in1\n\n\ndef lsim(system, U, T, X0=None, interp=1):\n \"\"\"\n Simulate output of a continuous-time linear system.\n\n Parameters\n ----------\n system : an instance of the LTI class or a tuple describing the system.\n The following gives the number of elements in the tuple and\n the interpretation:\n\n * 2: (num, den)\n * 3: (zeros, poles, gain)\n * 4: (A, B, C, D)\n\n U : array_like\n An input array describing the input at each time `T`\n (interpolation is assumed between given times). If there are\n multiple inputs, then each column of the rank-2 array\n represents an input.\n T : array_like\n The time steps at which the input is defined and at which the\n output is desired.\n X0 :\n The initial conditions on the state vector (zero by default).\n interp : {1, 0}\n Whether to use linear (1) or zero-order hold (0) interpolation.\n\n Returns\n -------\n T : 1D ndarray\n Time values for the output.\n yout : 1D ndarray\n System response.\n xout : ndarray\n Time-evolution of the state-vector.\n\n \"\"\"\n if isinstance(system, lti):\n sys = system\n else:\n sys = lti(*system)\n U = atleast_1d(U)\n T = atleast_1d(T)\n if len(U.shape) == 1:\n U = U.reshape((U.shape[0], 1))\n sU = U.shape\n if len(T.shape) != 1:\n raise ValueError(\"T must be a rank-1 array.\")\n if sU[0] != len(T):\n raise ValueError(\"U must have the same number of rows \"\n \"as elements in T.\")\n if sU[1] != sys.inputs:\n raise ValueError(\"System does not define that many inputs.\")\n\n if X0 is None:\n X0 = zeros(sys.B.shape[0], sys.A.dtype)\n\n xout = zeros((len(T), sys.B.shape[0]), sys.A.dtype)\n xout[0] = X0\n A = sys.A\n AT, BT = transpose(sys.A), transpose(sys.B)\n dt = T[1] - T[0]\n lam, v = linalg.eig(A)\n vt = transpose(v)\n vti = linalg.inv(vt)\n GT = dot(dot(vti, diag(numpy.exp(dt * lam))), vt)\n GT = _cast_to_array_dtype(GT, xout)\n\n ATm1 = linalg.inv(AT)\n ATm2 = dot(ATm1, ATm1)\n I = eye(A.shape[0], dtype=A.dtype)\n GTmI = GT - I\n F1T = dot(dot(BT, GTmI), ATm1)\n if interp:\n F2T = dot(BT, dot(GTmI, ATm2) / dt - ATm1)\n\n for k in xrange(1, len(T)):\n dt1 = T[k] - T[k - 1]\n if dt1 != dt:\n dt = dt1\n GT = dot(dot(vti, diag(numpy.exp(dt * lam))), vt)\n GT = _cast_to_array_dtype(GT, xout)\n GTmI = GT - I\n F1T = dot(dot(BT, GTmI), ATm1)\n if interp:\n F2T = dot(BT, dot(GTmI, ATm2) / dt - ATm1)\n\n xout[k] = dot(xout[k - 1], GT) + dot(U[k - 1], F1T)\n if interp:\n xout[k] = xout[k] + dot((U[k] - U[k - 1]), F2T)\n\n yout = (squeeze(dot(U, transpose(sys.D))) +\n squeeze(dot(xout, transpose(sys.C))))\n return T, squeeze(yout), squeeze(xout)\n\n\ndef _default_response_times(A, n):\n \"\"\"Compute a reasonable set of time samples for the response time.\n\n This function is used by `impulse`, `impulse2`, `step` and `step2`\n to compute the response time when the `T` argument to the function\n is None.\n\n Parameters\n ----------\n A : ndarray\n The system matrix, which is square.\n n : int\n The number of time samples to generate.\n\n Returns\n -------\n t : ndarray\n The 1-D array of length `n` of time samples at which the response\n is to be computed.\n \"\"\"\n # Create a reasonable time interval.\n # TODO: This could use some more work.\n # For example, what is expected when the system is unstable?\n vals = linalg.eigvals(A)\n r = min(abs(real(vals)))\n if r == 0.0:\n r = 1.0\n tc = 1.0 / r\n t = linspace(0.0, 7 * tc, n)\n return t\n\n\ndef impulse(system, X0=None, T=None, N=None):\n \"\"\"Impulse response of continuous-time system.\n\n Parameters\n ----------\n system : an instance of the LTI class or a tuple of array_like\n describing the system.\n The following gives the number of elements in the tuple and\n the interpretation:\n\n * 2 (num, den)\n * 3 (zeros, poles, gain)\n * 4 (A, B, C, D)\n\n X0 : array_like, optional\n Initial state-vector. Defaults to zero.\n T : array_like, optional\n Time points. Computed if not given.\n N : int, optional\n The number of time points to compute (if `T` is not given).\n\n Returns\n -------\n T : ndarray\n A 1-D array of time points.\n yout : ndarray\n A 1-D array containing the impulse response of the system (except for\n singularities at zero).\n\n \"\"\"\n if isinstance(system, lti):\n sys = system\n else:\n sys = lti(*system)\n if X0 is None:\n B = sys.B\n else:\n B = sys.B + X0\n if N is None:\n N = 100\n if T is None:\n T = _default_response_times(sys.A, N)\n else:\n T = asarray(T)\n\n h = zeros(T.shape, sys.A.dtype)\n s, v = linalg.eig(sys.A)\n vi = linalg.inv(v)\n C = sys.C\n for k in range(len(h)):\n es = diag(numpy.exp(s * T[k]))\n eA = dot(dot(v, es), vi)\n eA = _cast_to_array_dtype(eA, h)\n h[k] = squeeze(dot(dot(C, eA), B))\n\n return T, h\n\n\ndef impulse2(system, X0=None, T=None, N=None, **kwargs):\n \"\"\"\n Impulse response of a single-input, continuous-time linear system.\n\n Parameters\n ----------\n system : an instance of the LTI class or a tuple of array_like\n describing the system.\n The following gives the number of elements in the tuple and\n the interpretation:\n\n * 2 (num, den)\n * 3 (zeros, poles, gain)\n * 4 (A, B, C, D)\n\n X0 : 1-D array_like, optional\n The initial condition of the state vector. Default: 0 (the\n zero vector).\n T : 1-D array_like, optional\n The time steps at which the input is defined and at which the\n output is desired. If `T` is not given, the function will\n generate a set of time samples automatically.\n N : int, optional\n Number of time points to compute. Default: 100.\n kwargs : various types\n Additional keyword arguments are passed on to the function\n `scipy.signal.lsim2`, which in turn passes them on to\n `scipy.integrate.odeint`; see the latter's documentation for\n information about these arguments.\n\n Returns\n -------\n T : ndarray\n The time values for the output.\n yout : ndarray\n The output response of the system.\n\n See Also\n --------\n impulse, lsim2, integrate.odeint\n\n Notes\n -----\n The solution is generated by calling `scipy.signal.lsim2`, which uses\n the differential equation solver `scipy.integrate.odeint`.\n\n .. versionadded:: 0.8.0\n\n Examples\n --------\n Second order system with a repeated root: x''(t) + 2*x(t) + x(t) = u(t)\n\n >>> from scipy import signal\n >>> system = ([1.0], [1.0, 2.0, 1.0])\n >>> t, y = signal.impulse2(system)\n >>> import matplotlib.pyplot as plt\n >>> plt.plot(t, y)\n\n \"\"\"\n if isinstance(system, lti):\n sys = system\n else:\n sys = lti(*system)\n B = sys.B\n if B.shape[-1] != 1:\n raise ValueError(\"impulse2() requires a single-input system.\")\n B = B.squeeze()\n if X0 is None:\n X0 = zeros_like(B)\n if N is None:\n N = 100\n if T is None:\n T = _default_response_times(sys.A, N)\n\n # Move the impulse in the input to the initial conditions, and then\n # solve using lsim2().\n ic = B + X0\n Tr, Yr, Xr = lsim2(sys, T=T, X0=ic, **kwargs)\n return Tr, Yr\n\n\ndef step(system, X0=None, T=None, N=None):\n \"\"\"Step response of continuous-time system.\n\n Parameters\n ----------\n system : an instance of the LTI class or a tuple of array_like\n describing the system.\n The following gives the number of elements in the tuple and\n the interpretation:\n\n * 2 (num, den)\n * 3 (zeros, poles, gain)\n * 4 (A, B, C, D)\n\n X0 : array_like, optional\n Initial state-vector (default is zero).\n T : array_like, optional\n Time points (computed if not given).\n N : int\n Number of time points to compute if `T` is not given.\n\n Returns\n -------\n T : 1D ndarray\n Output time points.\n yout : 1D ndarray\n Step response of system.\n\n See also\n --------\n scipy.signal.step2\n\n \"\"\"\n if isinstance(system, lti):\n sys = system\n else:\n sys = lti(*system)\n if N is None:\n N = 100\n if T is None:\n T = _default_response_times(sys.A, N)\n else:\n T = asarray(T)\n U = ones(T.shape, sys.A.dtype)\n vals = lsim(sys, U, T, X0=X0)\n return vals[0], vals[1]\n\n\ndef step2(system, X0=None, T=None, N=None, **kwargs):\n \"\"\"Step response of continuous-time system.\n\n This function is functionally the same as `scipy.signal.step`, but\n it uses the function `scipy.signal.lsim2` to compute the step\n response.\n\n Parameters\n ----------\n system : an instance of the LTI class or a tuple of array_like\n describing the system.\n The following gives the number of elements in the tuple and\n the interpretation:\n\n * 2 (num, den)\n * 3 (zeros, poles, gain)\n * 4 (A, B, C, D)\n\n X0 : array_like, optional\n Initial state-vector (default is zero).\n T : array_like, optional\n Time points (computed if not given).\n N : int\n Number of time points to compute if `T` is not given.\n kwargs : various types\n Additional keyword arguments are passed on the function\n `scipy.signal.lsim2`, which in turn passes them on to\n `scipy.integrate.odeint`. See the documentation for\n `scipy.integrate.odeint` for information about these arguments.\n\n Returns\n -------\n T : 1D ndarray\n Output time points.\n yout : 1D ndarray\n Step response of system.\n\n See also\n --------\n scipy.signal.step\n\n Notes\n -----\n .. versionadded:: 0.8.0\n \"\"\"\n if isinstance(system, lti):\n sys = system\n else:\n sys = lti(*system)\n if N is None:\n N = 100\n if T is None:\n T = _default_response_times(sys.A, N)\n else:\n T = asarray(T)\n U = ones(T.shape, sys.A.dtype)\n vals = lsim2(sys, U, T, X0=X0, **kwargs)\n return vals[0], vals[1]\n\n\ndef bode(system, w=None, n=100):\n \"\"\"\n Calculate Bode magnitude and phase data of a continuous-time system.\n\n .. versionadded:: 0.11.0\n\n Parameters\n ----------\n system : an instance of the LTI class or a tuple describing the system.\n The following gives the number of elements in the tuple and\n the interpretation:\n\n * 2 (num, den)\n * 3 (zeros, poles, gain)\n * 4 (A, B, C, D)\n\n w : array_like, optional\n Array of frequencies (in rad/s). Magnitude and phase data is calculated\n for every value in this array. If not given a reasonable set will be\n calculated.\n n : int, optional\n Number of frequency points to compute if `w` is not given. The `n`\n frequencies are logarithmically spaced in an interval chosen to\n include the influence of the poles and zeros of the system.\n\n Returns\n -------\n w : 1D ndarray\n Frequency array [rad/s]\n mag : 1D ndarray\n Magnitude array [dB]\n phase : 1D ndarray\n Phase array [deg]\n\n Examples\n --------\n >>> from scipy import signal\n >>> import matplotlib.pyplot as plt\n\n >>> s1 = signal.lti([1], [1, 1])\n >>> w, mag, phase = signal.bode(s1)\n\n >>> plt.figure()\n >>> plt.semilogx(w, mag) # Bode magnitude plot\n >>> plt.figure()\n >>> plt.semilogx(w, phase) # Bode phase plot\n >>> plt.show()\n\n \"\"\"\n w, y = freqresp(system, w=w, n=n)\n\n mag = 20.0 * numpy.log10(abs(y))\n phase = numpy.unwrap(numpy.arctan2(y.imag, y.real)) * 180.0 / numpy.pi\n\n return w, mag, phase\n\n\ndef freqresp(system, w=None, n=10000):\n \"\"\"Calculate the frequency response of a continuous-time system.\n\n Parameters\n ----------\n system : an instance of the LTI class or a tuple describing the system.\n The following gives the number of elements in the tuple and\n the interpretation:\n\n * 2 (num, den)\n * 3 (zeros, poles, gain)\n * 4 (A, B, C, D)\n\n w : array_like, optional\n Array of frequencies (in rad/s). Magnitude and phase data is\n calculated for every value in this array. If not given a reasonable\n set will be calculated.\n n : int, optional\n Number of frequency points to compute if `w` is not given. The `n`\n frequencies are logarithmically spaced in an interval chosen to\n include the influence of the poles and zeros of the system.\n\n Returns\n -------\n w : 1D ndarray\n Frequency array [rad/s]\n H : 1D ndarray\n Array of complex magnitude values\n\n Examples\n --------\n # Generating the Nyquist plot of a transfer function\n\n >>> from scipy import signal\n >>> import matplotlib.pyplot as plt\n\n >>> s1 = signal.lti([], [1, 1, 1], [5])\n # transfer function: H(s) = 5 / (s-1)^3\n\n >>> w, H = signal.freqresp(s1)\n\n >>> plt.figure()\n >>> plt.plot(H.real, H.imag, \"b\")\n >>> plt.plot(H.real, -H.imag, \"r\")\n >>> plt.show()\n \"\"\"\n if isinstance(system, lti):\n sys = system\n else:\n sys = lti(*system)\n\n if sys.inputs != 1 or sys.outputs != 1:\n raise ValueError(\"freqresp() requires a SISO (single input, single \"\n \"output) system.\")\n\n if w is not None:\n worN = w\n else:\n worN = n\n\n # In the call to freqs(), sys.num.ravel() is used because there are\n # cases where sys.num is a 2-D array with a single row.\n w, h = freqs(sys.num.ravel(), sys.den, worN=worN)\n\n return w, h\n" ]
[ [ "numpy.product", "numpy.dot", "numpy.exp", "numpy.issubdtype", "scipy.linalg.eigvals", "numpy.zeros_like", "numpy.eye", "scipy.linalg.eig", "numpy.transpose", "numpy.atleast_2d", "numpy.array", "scipy.interpolate.interp1d", "numpy.zeros", "numpy.real", "scipy.linalg.inv", "numpy.arctan2", "numpy.squeeze", "scipy.integrate.odeint", "numpy.asarray", "numpy.ones", "numpy.poly", "numpy.atleast_1d", "numpy.ravel", "numpy.linspace" ] ]
JasonWherry/SamplingApp
[ "604df918c52ef7e4f3555203dc9e6c9c9f0511e9" ]
[ "old.py" ]
[ "\"\"\"\nAuthor: Jason Wherry\tStart Date: 5/08/2020\t\tTo Run: python3 main.py\n\nWhat am I actually plotting? --> The means calculated from each sample\n\nIdeas:\n - Add tests to unit_tests.py to test the functions\n\n - Add the following to menu option #1 (to educate the user)\n\t- make a histogram of the population without the means; plot just the raw scores\n\t- include pictures of the distributions\n\t- provide a real world example for each distribution; Explain how they're applicable\n\n - Add the following to menu option #2\n\t- plot the mean of means in realtime; Show the user how samples build from 1 case up to 640 cases\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom pandas import DataFrame\nimport seaborn as sb\nimport matplotlib.pyplot as plt\nfrom statistics import *\nimport scipy.stats as stats\n\n\n\"\"\"\n prompt_user()\n \t- objective:\t\tgather data aligned with user's request\n\t- parameter:\t \tNone\n\t- return:\t\t\tDataFrame – filled with values randomly generated between 0 & 1\n\"\"\"\ndef prompt_user(distribution):\n\tpopulation = input('\\nEnter \\'q\\' to quit\\nChoose a Population size - 3200 6400 9600, default=3200: ') #3200\n\tpopulation_sizes = ['3200', '6400', '9600']\n\t\n\t# check input to stop code execution\n\tif population == 'q' or population == 'Q':\n\t\texit()\n\tif population == '':\n\t\tpopulation = '3200'\n\n\twhile population not in population_sizes:\n\t\tprint(population, ' - invalid population')\n\t\tpopulation = input('\\nEnter \\'q\\' to quit\\nChoose a Population size - 3200 6400 9600, default=3200: ')\n\t\t\n\t\t# check input to stop code execution\n\t\tif population == 'q' or population == 'Q':\n\t\t\texit()\n\t\tif population == '':\n\t\t\tpopulation = '3200'\n\n\tprint('\\npopulation =', population)\n\n\tcase_sizes = ['1', '40', '80', '160', '320', '640']\n\tcases = input('\\n\\tEnter \\'q\\' to quit\\n\\n\\tChoose the number of cases – 1 40 80 160 320 640: ')\n\n\t# check input to stop code execution\n\tif cases == 'q' or cases == 'Q':\n\t\texit()\n\n\twhile cases not in case_sizes:\n\t\tprint(cases, ' - invalid case')\n\t\tcases = input('\\nEnter \\'q\\' to quit\\nChoose the number of cases – 1 40 80 160 320 640: ')\n\t\t\n\t\t# check input to stop code execution\n\t\tif cases == 'q' or cases == 'Q':\n\t\t\texit()\n\n\tprint('cases =', cases)\n\n\tpopulation_int = int(population)\n\n\tsamples = int(population_int / int(cases) )\n\tprint('samples =', str(samples) )\n\tprint('\\n')\n\n\t# empty data frame to hold the data; each column is a case\n\tdf = pd.DataFrame(data=None)\n\n\t# fill the DataFrame with data;\t\tdf.shape = [samples X cases]\n\t# each column is a sample case with the number of values equal to the ratio (population/cases)\n\n\tif distribution == 'Uniform':\n\t\tfor i in range(0, int(cases) ):\n\t\t\ttemp = pd.Series(np.random.uniform(0, 1.0, samples))\n\t\t\tcol_name = 'Case ' + str(i+1)\n\t\t\tdf.insert(i, col_name, temp)\n\n\t# elif distribution == 'Bernoulli':\n\t\t# for i in range(0, int(cases) ):\n\t\t# \ttemp = pd.Series(np.random.binomial(1, 0.5, samples))\n\t\t# \tcol_name = 'Case ' + str(i+1)\n\t\t# \tdf.insert(i, col_name, temp)\n\t\t# # Not working at the moment\n\n\telif distribution == 'Binomial':\n\t\tResp = False\n\t\tvalid = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']\n\t\twhile not Resp:\n\t\t\tprob = input('Note: hit \\'enter\\' for default 50-50 chance\\nChoose the probablity as a percentage, i.e. 0, 30, 70: ')\n\t\t\tprint('prob ', prob)\n\t\t\tif prob == '':\n\t\t\t\tprobNum = 0.5\n\t\t\t\tResp = True\n\t\t\telif prob[:2] in valid: # 100% == 10 in valid\n\t\t\t\tprobNum = int(prob[:2])/10.0\n\t\t\t\tResp = True\n\t\t\telif prob[0] in valid:\n\t\t\t\tprobNum = int(prob[0])/10.0\n\t\t\t\tResp = True\n\t\t\t\n\n\t\tfor i in range(0, int(cases) ):\n\t\t\t# temp = pd.Series(np.random.binomial(1, 0.5, samples)) # flip a coin 1 time, tested samples times\n\t\t\ttemp = pd.Series(np.random.binomial(1, probNum, samples)) # flip a coin 1 time, tested samples times\n\t\t\tcol_name = 'Case ' + str(i+1)\n\t\t\tdf.insert(i, col_name, temp)\n\n\t\treturn df, distribution, probNum\n\n\telif distribution == 'Normal':\n\t\tfor i in range(0, int(cases) ):\n\t\t\ttemp = pd.Series(np.random.normal(0.5, 0.1, samples))\n\t\t\tcol_name = 'Case ' + str(i+1)\n\t\t\tdf.insert(i, col_name, temp)\n\n\tprint(df, '\\n') # display np.random.uniform numbers (dtype is float64) by sample\n\t# print(df.shape)\n\n\treturn df, distribution, None\n\n\n\"\"\"\n find_mean(data_frame)\n \t- objective:\t\tdetermine the mean of the chosen sample(s)\n\t- parameter:\t \tpandas DataFrame, type of distribution\n\t- return:\t\t\tSeries – means & std. deviations\n\"\"\"\ndef find_stats(df, dist_type, probNum = None):\n\tmeans = []\n\tsample_num = len(df.columns) \t# AKA cases\n\tsample_size = len(df)\t\t\t# AKA samples per case\n\tdist_type = dist_type + ' Distribution - ' + str(sample_num) + ' Cases that sample ' + str(sample_size) + ' numbers'\n\n\tprint('number of cases:\\t', sample_num, '\\nsamples per case:\\t', sample_size)\n\tprint('\\n')\n\tif probNum:\n\t\ttemp = str(probNum*100) + '%'\n\t\tprint('Probablity of Binomial distribution:\\t', temp)\n\t\n\t# loop through each sample and find its respective mean\n\tfor i in range(0, sample_num):\n\t\tmean = round( df.iloc[0:, i].mean(), 3) # mean of sample size from generated random values\n\t\tmeans.append(mean)\n\n\tif sample_num == 1:\n\t\t# there is one sample & we need more than 1 value to calculate std_dev\n\t\t# std_dev = round( df.iloc[0:, i].std(), 3) # old way to calculate std_dev for just 1 sample\n\n\t\tmean_of_means = means[0]\n\t\tstd_dev = round( df.iloc[0:, i].mean().std(), 3)\n\t\tvariance = round( df.iloc[0:, i].mean().var(), 3)\n\t\tskewness = round( df.iloc[0:, i].skew(), 3)\n\t\tkurtosis = round( df.iloc[0:, i].kurtosis(), 3)\n\n\t\t# Turn array of means into a numpy array\n\t\tnumpy_means = np.array(means)\n\n\t\tfig = plt.subplot()\n\t\tfig.hist(numpy_means, bins=50, range=[0,1], histtype='bar')\n\t\tfig.set_xlabel('Mean (Value)')\n\t\tfig.set_ylabel('Value Frequency')\n\t\tfig.set_title(dist_type)\n\t\tplt.show()\n\t\t\n\t\treturn means, mean_of_means, variance, std_dev, skewness, kurtosis\n\n\telse:\n\t\t# Turn array of means into a numpy array\n\t\tnumpy_means = np.array(means)\n\n\t\tfig = plt.subplot()\n\t\tfig.hist(numpy_means, bins=50, range=[0,1], histtype='bar')\n\t\tfig.set_xlabel('Mean (Value)')\n\t\tfig.set_ylabel('Value Frequency')\n\t\tfig.set_title(dist_type)\n\t\tplt.show()\n\n\t\tmean_of_means = round( numpy_means.mean(), 3)\n\t\tvariance = round( stats.tvar(means), 3)\n\t\tstd_dev = round( stdev(means), 3)\n\t\tskewness = round( stats.skew(means), 3)\n\t\tkurtosis = round( stats.kurtosis(means), 3)\n\n\n\t\treturn means, mean_of_means, variance, std_dev, skewness, kurtosis\n\n\n\"\"\"\n find_mean(data_frame)\n \t- objective:\t\tdisplay content of lists\n\t- parameter:\t \tpandas Series\n\t- return:\t\t\tNone\n\"\"\"\ndef display_stats(means, mean_of_means, variance, std_dev, skewness, kurtosis):\n\t# for i in range(0, len(means)):\n\t# \tprint('\\tsample number', i+1, '\\tmean\\t', means[i])\n\n\tprint('\\n')\n\t# print('\\t\\t\\t\\t|–––––––––––––––––––––––––––––––|')\n\tprint('\\t\\t\\t|–––––––––––––––––––––––|')\n\tprint('\\t\\t\\t mean of means ', mean_of_means)\n\tprint('\\t\\t\\t variance\\t', variance)\n\tprint('\\t\\t\\t std. deviation', std_dev)\n\tprint('\\t\\t\\t skewness\\t', skewness)\n\tprint('\\t\\t\\t kurtosis\\t', kurtosis)\n\t# print('\\t\\t\\t\\t|\\t\\t\\t\\t|')\n\tprint('\\t\\t\\t|–––––––––––––––––––––––|')\n\tprint('\\n\\n')\n\n\n\"\"\"\n test()\n \t- objective:\t\truns the program functions\n\t- parameter:\t \tnumber of runs desired, selected distribution\n\t- return:\t\t\tNone\n\"\"\"\ndef test(num_runs, dist):\n\twhile num_runs > 0:\n\t\trun, dist, Prob = prompt_user(dist) # returns a data frame\n\t\tmeans, mean_of_means, variance, std_dev, skew, kurt = find_stats(run, dist, Prob)\n\t\tdisplay_stats(means, mean_of_means, variance, std_dev, skew, kurt)\n\n\t\tnum_runs -= 1\n\n\n# test(1, 'Normal') # run once\n\n\"\"\"\neducate()\n\t- objective:\t\tProvide user with a list of options to run the program\n\t- parameter:\t\tNone\n\t- return:\t\t\tUser's request\n\"\"\"\ndef educate():\n\t# Violating the principle: DNRY ~ Do Not Repeat Yourself\n\n\tprint('A Uniform distribution...')\n\n\t# generate histogram of the raw scores\n\tunifVals = pd.Series(np.random.uniform(0, 1.0, 3200))\n\tnormVals = pd.Series(np.random.normal(0.5, 0.1, 3200))\n\tbinVals = pd.Series(np.random.binomial(1, 0.5, 3200))\n\n\tuniFig = plt.subplot()\n\tuniFig.hist(unifVals, bins=50, range=[0,1], histtype='bar')\n\tuniFig.set_xlabel('Mean (Value)')\n\tuniFig.set_ylabel('Value Frequency')\n\tuniFig.set_title('Uniform Raw Scores')\n\tplt.show()\n\n\t# print('A Bernoulli distribution...')\n\n\tprint('A Normal distribution...')\n\tnormFig = plt.subplot()\n\tnormFig.hist(normVals, bins=50, range=[0,1], histtype='bar')\n\tnormFig.set_xlabel('Mean (Value)')\n\tnormFig.set_ylabel('Value Frequency')\n\tnormFig.set_title('Normal Raw Scores')\n\tplt.show()\n\n\n\tprint('A Binomial distribution...')\n\tbinFig = plt.subplot()\n\tbinFig.hist(binVals, bins=50, range=[0,1], histtype='bar')\n\tbinFig.set_xlabel('Mean (Value)')\n\tbinFig.set_ylabel('Value Frequency')\n\tbinFig.set_title('Binomial Raw Scores')\n\tplt.show()\n\n\"\"\"\n menu()\n\t- objective:\t\tProvide user with a list of options to run the program\n\t- parameter:\t\tNone\n\t- return:\t\t\tUser's request\n\"\"\"\ndef menu(test_input=''):\n\tprint('\\n Menu')\n\tprint('\\t1 : distributions -> lists alternative distribution choices')\n\tprint('\\t2 : demonstration -> demonstrates the Central Limit Theorem with random sampling')\n\tprint('\\t3 : quit -> terminates program execution')\n\n\tif test_input:\n\t\tuser_input = test_input\n\telse:\n\t\tuser_input = input('\\n Enter one of the following options: \\'1\\', \\'2\\', \\'3\\': ')\n\n\t# print(user_input)\n\tprint('\\n')\n\n\t# case analysis on user input\n\tif user_input == '1':\n\t\teducate()\n\t\tmenu() # display menu again\n\telif user_input == '2':\n\t\tResp = False\n\t\tvalid = ['1', '2', '3']\n\t\tcounter = 0\n\t\twhile not Resp:\n\t\t\tif counter > 4:\n\t\t\t\tprint('Incorrect Input for \\'distribution type\\' : Program execution terminated')\n\t\t\t\texit()\n\t\t\tprint('\\n Select a distribution type')\n\t\t\tprint('\\t1 : Uniform')\n\t\t\t# print('\\t2 : Bernoulli')\n\t\t\tprint('\\t2 : Binomial')\n\t\t\tprint('\\t3 : Normal')\n\t\t\t\n\t\t\tdist_type = input('\\n Enter one of the following options: \\'1\\', \\'2\\', \\'3\\': ')\n\n\t\t\tif dist_type not in valid:\n\t\t\t\tcounter += 1\n\t\t\t\tResp = False\n\n\t\t\telif dist_type == '1':\n\t\t\t\ttest(1, 'Uniform')\n\t\t\t\tResp = True\n\t\t\t# elif dist_type == '2':\n\t\t\t# \ttest(1, 'Bernoulli')\n\t\t\telif dist_type == '2':\t\n\t\t\t\ttest(1, 'Binomial')\n\t\t\t\tResp = True\n\t\t\telif dist_type == '3':\n\t\t\t\ttest(1, 'Normal')\n\t\t\t\tResp = True\n\n\t\t\t# menu() # display menu again\n\n\telif user_input == '3':\n\t\texit()\n\n\nmenu()\n\n" ]
[ [ "numpy.random.normal", "numpy.array", "numpy.random.binomial", "pandas.DataFrame", "scipy.stats.skew", "numpy.random.uniform", "matplotlib.pyplot.show", "scipy.stats.kurtosis", "scipy.stats.tvar", "matplotlib.pyplot.subplot" ] ]
srichers/thornado
[ "bc6666cbf9ae8b39b1ba5feffac80303c2b1f9a8" ]
[ "Workflow/AMReX/AMReX_MakeMovie_2D_Spherical_TwoFields.py" ]
[ "#!/usr/bin/env python3\n\n\"\"\"\nGenerate a movie showing two fields side-by-side\nfrom data files created in MakeDataFiles.py.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\nimport subprocess\n\n# --- Get user's HOME directory ---\nHOME = subprocess.check_output( [\"echo $HOME\"], shell = True)\nHOME = HOME[:-1].decode( \"utf-8\" ) + '/'\n\n############# User input #############\n\n# First\n\nRoot1 = 'M1.4_Rs180_Mdot0.3'\nsuffix1 = ''\n\nDataDirectory1 = HOME + '{:}/'.format( Root1 )\n\nPlotFileBaseName1 = 'plt_{:}{:}'.format( Root1, suffix1 )\n\nField1 = 'PolytropicConstant' # Field to plot\n\ncmap1 = 'Purples' # Color scheme\n\nUseLogScale1 = True # Use log scale?\n\n# Second\n\nRoot2 = 'M1.4_Rs180_Mdot0.3'\nsuffix2 = ''\n\nDataDirectory2 = HOME + '{:}/'.format( Root2 )\n\nPlotFileBaseName2 = 'plt_{:}{:}'.format( Root2, suffix2 )\n\nField2 = 'PolytropicConstant' # Field to plot\n\ncmap2 = 'Purples' # Color scheme\n\nUseLogScale2 = True # Use log scale?\n\n# Global\n\nMovieName = 'SASI_{:}_{:}'.format( Field1, Field2 )\n\nMovieRunTime = 30.0 # seconds\n\nUsePhysicalUnits = True # Does your data use physical units?\n\nUseCustomTicks = True # Define limits for colorbar near line 70\n\nzAxisVertical = True # Orient z-axis\n\n############# End of user input #############\n\nID1 = '{:}{:}_{:}'.format( Root1, suffix1, Field1 )\nDataFileName1 = '{:}_MovieData.dat'.format( ID1 )\nTimeFileName1 = '{:}_MovieTime.dat'.format( ID1 )\n\nID2 = '{:}{:}_{:}'.format( Root2, suffix2, Field2 )\nDataFileName2 = '{:}_MovieData.dat'.format( ID2 )\nTimeFileName2 = '{:}_MovieTime.dat'.format( ID2 )\n\nfrom MakeDataFiles import *\n\nxL, xH, nX, FileArray1 \\\n = MakeDataFile( Field1, DataDirectory1, DataFileName1, TimeFileName1, \\\n PlotFileBaseName1, UsePhysicalUnits )\n\nxL, xH, nX, FileArray2 \\\n = MakeDataFile( Field2, DataDirectory2, DataFileName2, TimeFileName2, \\\n PlotFileBaseName2, UsePhysicalUnits )\n\nprint( 'Reading in data files...' )\n\nData1 = np.loadtxt( DataFileName1 ).reshape( \\\n (FileArray1.shape[0],nX[0],nX[1]) )\nData2 = np.loadtxt( DataFileName2 ).reshape( \\\n (FileArray2.shape[0],nX[0],nX[1]) )\n\nTime = np.loadtxt( TimeFileName1 ) # These should be the same for both fields\n\nfig = plt.figure( figsize = (8,6) )\nax = fig.add_subplot( 111, polar = True )\nxL = xL.to_ndarray()\nxH = xH.to_ndarray()\nX1 = np.linspace( xL[0], xH[0], nX[0] )\nX2 = np.linspace( xL[1], xH[1], nX[1] )\ntheta1, r = np.meshgrid( X2, X1 )\ntheta2, r = np.meshgrid( 2.0 * np.pi - X2, X1 )\n\nif( UseCustomTicks ):\n\n vmin1 = min( +np.inf, np.min( Data1 ) )\n vmax1 = max( -np.inf, np.max( Data1 ) )\n vmin2 = min( +np.inf, np.min( Data2 ) )\n vmax2 = max( -np.inf, np.max( Data2 ) )\n\n if( UseLogScale1 ):\n\n if ( vmax1 < 0.0 ):\n ticks1 = np.linspace( -np.log10(-vmin1), -np.log10(-vmax1), 5 )\n elif( vmin1 < 0.0 ):\n ticks1 = np.linspace( -np.log10(-vmin1), +np.log10(+vmax1), 5 )\n else:\n ticks1 = np.logspace( +np.log10(+vmin1), +np.log10(+vmax1), 5 )\n\n else:\n\n ticks1 = np.linspace( vmin1, vmax1, 5 )\n\n if( UseLogScale2 ):\n\n if ( vmax2 < 0.0 ):\n ticks2 = np.linspace( -np.log10(-vmin2), -np.log10(-vmax2), 5 )\n elif( vmin2 < 0.0 ):\n ticks2 = np.linspace( -np.log10(-vmin2), +np.log10(+vmax2), 5 )\n else:\n ticks2 = np.logspace( +np.log10(+vmin2), +np.log10(+vmax2), 5 )\n\n else:\n\n ticks2 = np.linspace( vmin2, vmax2, 5 )\n\n ticklabels1 = []\n ticklabels2 = []\n for tick in ticks1:\n ticklabels1.append( '{:.3e}'.format( tick ) )\n for tick in ticks2:\n ticklabels2.append( '{:.3e}'.format( tick ) )\n\nelse:\n\n vmin1 = min( +np.inf, np.min( Data1 ) )\n vmax1 = max( -np.inf, np.max( Data1 ) )\n vmin2 = min( +np.inf, np.min( Data2 ) )\n vmax2 = max( -np.inf, np.max( Data2 ) )\n\nif( UseLogScale1 ):\n\n from matplotlib.colors import LogNorm, SymLogNorm\n\n if( np.any( Data1 < 0.0 ) ):\n Norm1 = SymLogNorm( vmin = vmin1, vmax = vmax1, \\\n linthresh = 1.0e2, base = 10 )\n else:\n Norm1 = LogNorm ( vmin = vmin1, vmax = vmax1 )\n\nelse:\n\n Norm1 = plt.Normalize ( vmin = vmin1, vmax = vmax1 )\n\nif( UseLogScale2 ):\n\n from matplotlib.colors import LogNorm, SymLogNorm\n\n if( np.any( Data2 < 0.0 ) ):\n Norm2 = SymLogNorm( vmin = vmin2, vmax = vmax2, \\\n linthresh = 1.0e2, base = 10 )\n else:\n Norm2 = LogNorm ( vmin = vmin2, vmax = vmax2 )\n\nelse:\n\n Norm2 = plt.Normalize ( vmin = vmin2, vmax = vmax2 )\n\ndef f1(t):\n return Data1[t]\ndef f2(t):\n return Data2[t]\n\n# Taken from:\n# https://brushingupscience.com/2016/06/21/matplotlib-animations-the-easy-way/\nim1 = ax.pcolormesh( theta1, r, f1(0)[:-1,:-1], \\\n cmap = cmap1, \\\n norm = Norm1 )\nim2 = ax.pcolormesh( theta2, r, f2(0)[:-1,:-1], \\\n cmap = cmap2, \\\n norm = Norm2 )\n\n# Limits on coordinate axes\n\nax.set_thetamin( 0.0 )\nax.set_thetamax( 360.0 )\nax.set_theta_direction( -1 )\nax.set_xticklabels( [] )\n\nif( zAxisVertical ):\n ax.set_theta_zero_location( 'N' ) # z-axis vertical\n time_text = plt.text( 0.1 * np.pi / 2.0, xH[0] * ( 1.0 + 0.1 ), '' )\nelse:\n ax.set_theta_zero_location( 'W' ) # z-axis horizontal\n time_text = plt.text( 0.9 * np.pi / 2.0, xH[0] * ( 1.0 + 0.3 ), '' )\n\ncb1axes = fig.add_axes( [ 0.81, 0.1, 0.03, 0.8 ] )\ncb2axes = fig.add_axes( [ 0.185, 0.1, 0.03, 0.8 ] )\nif( UseCustomTicks ):\n cbar1 = fig.colorbar( im1, cax = cb1axes, ticks = ticks1 )\n cbar1.ax.set_yticklabels( ticklabels1 )\n cbar2 = fig.colorbar( im2, cax = cb2axes, ticks = ticks2 )\n cbar2.ax.set_yticklabels( ticklabels2 )\nelse:\n cbar1 = fig.colorbar( im1, cax = cb1axes )\n cbar2 = fig.colorbar( im2, cax = cb2axes )\ncbar1.ax.set_ylabel( Field1 )\ncbar2.ax.set_ylabel( Field2 )\n\ncb2axes.yaxis.set_ticks_position( 'left' )\ncb2axes.yaxis.set_label_position( 'left' )\n\nTimeUnit = ''\nif( UsePhysicalUnits ): TimeUnit = ' ms'\n\ndef UpdateFrame(t):\n im1.set_array( f1(t)[:-1,:-1].flatten() )\n im2.set_array( f2(t)[:-1,:-1].flatten() )\n time_text.set_text('time = {:d}{:}'.format( np.int( Time[t] ), TimeUnit ) )\n return im1, im2,\n\n# Call the animator\n\nprint( 'Making movie...' )\n\nnFrames = max( FileArray1.shape[0], FileArray2.shape[0] )\nfps = nFrames / MovieRunTime\n\nanim \\\n = animation.FuncAnimation \\\n ( fig, UpdateFrame, frames = nFrames, blit = True )\n\nanim.save( '{:}_Movie.mp4'.format( MovieName ), fps = fps )\nplt.close()\n\nimport os\nos.system( 'rm -rf __pycache__ ' )\n" ]
[ [ "numpy.max", "numpy.log10", "matplotlib.pyplot.text", "numpy.int", "matplotlib.animation.FuncAnimation", "matplotlib.pyplot.close", "numpy.min", "matplotlib.pyplot.figure", "numpy.any", "numpy.loadtxt", "matplotlib.colors.SymLogNorm", "matplotlib.pyplot.Normalize", "numpy.linspace", "numpy.meshgrid", "matplotlib.colors.LogNorm" ] ]
wiki-yu/fastapi-algorithm-library
[ "8f745e9fe4d1d063dc8505d4c7f467e95209a385" ]
[ "app/libs/action_localization/spatio_temporal_pytorch/datasets/dataset.py" ]
[ "#!/usr/bin/python\n# encoding: utf-8\n\nimport os\nimport random\nimport torch\nimport numpy as np\nfrom torch.utils.data import Dataset\nfrom PIL import Image\nfrom datasets.clip import *\nimport glob\n\nclass listDataset(Dataset):\n\n # clip duration = 8, i.e, for each time 8 frames are considered together\n def __init__(self, base, root, dataset_use='ucf101-24', shape=None, shuffle=False,\n transform=None, target_transform=None, \n train=False, seen=0, batch_size=64,\n clip_duration=16, num_workers=1):\n with open(root, 'r') as file:\n self.lines = file.readlines()\n\n if shuffle:\n random.shuffle(self.lines)\n\n self.base_path = base\n self.dataset_use = dataset_use\n self.nSamples = len(self.lines)\n self.transform = transform\n self.target_transform = target_transform\n self.train = train\n self.shape = shape\n self.seen = seen\n self.batch_size = batch_size\n self.clip_duration = clip_duration\n self.num_workers = num_workers\n print('### Dataset init: base path: {}, dataset: {}, workers: {}'.format(self.base_path, self.dataset_use, self.num_workers))\n\n def __len__(self):\n return self.nSamples\n\n def __getitem__(self, index):\n assert index <= len(self), 'index range error'\n imgpath = self.lines[index].rstrip()\n self.shape = (224, 224)\n\n if self.train: # For Training\n jitter = 0.2\n hue = 0.1\n saturation = 1.5 \n exposure = 1.5\n\n clip, label = load_data_detection(self.base_path, imgpath, self.train, self.clip_duration, self.shape, self.dataset_use, jitter, hue, saturation, exposure)\n\n else: # For Testing\n frame_idx, clip, label = load_data_detection(self.base_path, imgpath, False, self.clip_duration, self.shape, self.dataset_use)\n clip = [img.resize(self.shape) for img in clip]\n\n\n if self.transform is not None:\n clip = [self.transform(img) for img in clip]\n\n # (self.duration, -1) + self.shape = (8, -1, 224, 224)\n clip = torch.cat(clip, 0).view((self.clip_duration, -1) + self.shape).permute(1, 0, 2, 3)\n\n if self.target_transform is not None:\n label = self.target_transform(label)\n\n self.seen = self.seen + self.num_workers\n\n if self.train:\n return (clip, label)\n else:\n return (frame_idx, clip, label)\n\nclass testData(Dataset):\n\n # clip duration = 8, i.e, for each time 8 frames are considered together\n def __init__(self, root, shape=None, shuffle=False,\n transform=None, target_transform=None,\n train=False, seen=0, batch_size=64,\n clip_duration=16, num_workers=4):\n self.root = root\n self.imgpaths = sorted(glob.glob(os.path.join(root, '*.jpg')))\n\n if shuffle:\n random.shuffle(self.lines)\n\n self.nSamples = len(self.imgpaths)\n self.transform = transform\n self.target_transform = target_transform\n self.train = train\n self.shape = shape\n self.seen = seen\n self.batch_size = batch_size\n self.clip_duration = clip_duration\n self.num_workers = num_workers\n\n def __len__(self):\n return self.nSamples\n\n def __getitem__(self, index):\n assert index <= len(self), 'index range error'\n imgpath = self.imgpaths[index]\n\n clip,label = load_data_detection_test(self.root, imgpath, self.clip_duration, self.nSamples)\n clip = [img.resize(self.shape) for img in clip]\n\n if self.transform is not None:\n clip = [self.transform(img) for img in clip]\n\n clip = torch.cat(clip, 0).view((self.clip_duration, -1) + self.shape).permute(1, 0, 2, 3)\n\n if self.target_transform is not None:\n label = self.target_transform(label)\n\n self.seen = self.seen + self.num_workers\n return clip,label\n" ]
[ [ "torch.cat" ] ]
tensorturtle/CSI-Camera
[ "3aaa7ddbc574a2e9c3bdcf6c47db27a91ebb5345" ]
[ "instrumented/dual_camera_naive.py" ]
[ "# MIT License\n# Copyright (c) 2019 JetsonHacks\n# See license\n# Using a CSI camera (such as the Raspberry Pi Version 2) connected to a\n# NVIDIA Jetson Nano Developer Kit using OpenCV\n# Drivers for the camera and OpenCV are included in the base image\n\nimport cv2\nfrom timecontext import Timer\nimport numpy as np\n\n# gstreamer_pipeline returns a GStreamer pipeline for capturing from the CSI camera\n# Defaults to 1280x720 @ 60fps\n# Flip the image by setting the flip_method (most common values: 0 and 2)\n# display_width and display_height determine the size of the window on the screen\n\n\ndef gstreamer_pipeline(\n sensor_id=0,\n sensor_mode=3,\n capture_width=1280,\n capture_height=720,\n display_width=1280,\n display_height=720,\n framerate=60,\n flip_method=0,\n):\n return (\n \"nvarguscamerasrc sensor-id=%d sensor-mode=%d ! \"\n \"video/x-raw(memory:NVMM), \"\n \"width=(int)%d, height=(int)%d, \"\n \"format=(string)NV12, framerate=(fraction)%d/1 ! \"\n \"nvvidconv flip-method=%d ! \"\n \"video/x-raw, width=(int)%d, height=(int)%d, format=(string)BGRx ! \"\n \"videoconvert ! \"\n \"video/x-raw, format=(string)BGR ! appsink\"\n % (\n sensor_id,\n sensor_mode,\n capture_width,\n capture_height,\n framerate,\n flip_method,\n display_width,\n display_height,\n )\n )\n\n\ndef show_camera():\n # To flip the image, modify the flip_method parameter (0 and 2 are the most common)\n print(gstreamer_pipeline(flip_method=0))\n left_cap = cv2.VideoCapture(\n gstreamer_pipeline(flip_method=0,display_width=960,display_height=540,framerate=30), cv2.CAP_GSTREAMER)\n right_cap = cv2.VideoCapture(gstreamer_pipeline(\n flip_method=0, sensor_id=1,display_width=960,display_height=540,framerate=30), cv2.CAP_GSTREAMER)\n if left_cap.isOpened():\n cv2.namedWindow(\"CSI Camera\", cv2.WINDOW_AUTOSIZE)\n # Window\n while cv2.getWindowProperty(\"CSI Camera\", 0) >= 0:\n with Timer() as context_time:\n ret_val, left_image = left_cap.read()\n ret_val, right_image = right_cap.read()\n # print(context_time.elapsed)\n # We place both images side by side to show in the window\n camera_images = np.hstack((left_image, right_image))\n cv2.imshow(\"CSI Cameras\", camera_images)\n # cv2.imshow(\"CSI Camera\", left_image)\n # print(context_time.elapsed)\n\n # This also acts as\n keyCode = cv2.waitKey(20) & 0xFF\n # print(context_time.elapsed)\n # print(\"---\")\n # Stop the program on the ESC key\n if keyCode == 27:\n break\n left_cap.release()\n right_cap.release()\n cv2.destroyAllWindows()\n else:\n print(\"Unable to open camera\")\n\n\nif __name__ == \"__main__\":\n show_camera()\n" ]
[ [ "numpy.hstack" ] ]
poypoyan/edhmm
[ "4d8a1fafa69a1d69e4a99963436179db4a91d7a5" ]
[ "edhsmm/hsmm_base.py" ]
[ "import numpy as np\nfrom scipy.stats import multivariate_normal\nfrom scipy.special import logsumexp\nfrom sklearn import cluster\nfrom sklearn.utils import check_array\n\nfrom . import _hsmm_core as core, hsmm_utils\nfrom .hsmm_utils import log_mask_zero, iter_from_X_lengths\n\n\n# Base Class for Explicit Duration HSMM\nclass HSMM:\n def __init__(self, n_states=2, n_durations=5, n_iter=20, tol=1e-2, random_state=None):\n if not n_states >= 2:\n raise ValueError(\"number of states (n_states) must be at least 2\")\n if not n_durations >= 1:\n raise ValueError(\"number of durations (n_durations) must be at least 1\")\n self.n_states = n_states\n self.n_durations = n_durations\n self.n_iter = n_iter\n self.tol = tol\n self.random_state = random_state\n\n # _init: initializes model parameters if there are none yet\n def _init(self):\n if not hasattr(self, \"pi\"):\n self.pi = np.full(self.n_states, 1.0 / self.n_states)\n if not hasattr(self, \"tmat\"):\n self.tmat = np.full((self.n_states, self.n_states), 1.0 / (self.n_states - 1))\n for i in range(self.n_states):\n self.tmat[i, i] = 0.0 # no self-transitions in EDHSMM\n self._dur_init() # duration\n\n # _check: check if properties of model parameters are satisfied\n def _check(self):\n # starting probabilities\n self.pi = np.asarray(self.pi)\n if self.pi.shape != (self.n_states, ):\n raise ValueError(\"start probabilities (self.pi) must have shape ({},)\".format(self.n_states))\n if not np.allclose(self.pi.sum(), 1.0):\n raise ValueError(\"start probabilities (self.pi) must add up to 1.0\")\n # transition probabilities\n self.tmat = np.asarray(self.tmat)\n if self.tmat.shape != (self.n_states, self.n_states):\n raise ValueError(\"transition matrix (self.tmat) must have shape ({0}, {0})\".format(self.n_states))\n if not np.allclose(self.tmat.sum(axis=1), 1.0):\n raise ValueError(\"transition matrix (self.tmat) must add up to 1.0\")\n for i in range(self.n_states):\n if self.tmat[i, i] != 0.0: # check for diagonals\n raise ValueError(\"transition matrix (self.tmat) must have all diagonals equal to 0.0\")\n # duration probabilities\n self._dur_check()\n\n # _dur_init: initializes duration parameters if there are none yet\n def _dur_init(self):\n \"\"\"\n arguments: (self)\n return: None\n > initialize the duration parameters\n \"\"\"\n pass # implemented in subclass\n\n # _dur_check: checks if properties of duration parameters are satisfied\n def _dur_check(self):\n \"\"\"\n arguments: (self)\n return: None\n > check the duration parameters\n \"\"\"\n pass # implemented in subclass\n\n # _dur_probmat: compute the probability per state of each duration\n def _dur_probmat(self):\n \"\"\"\n arguments: (self)\n return: duration probability matrix\n \"\"\"\n pass # implemented in subclass\n\n # _dur_mstep: perform m-step for duration parameters\n def _dur_mstep(self):\n \"\"\"\n arguments: (self, new_dur)\n return: None\n > compute the duration parameters\n \"\"\"\n pass # implemented in subclass\n\n # _emission_logl: compute the log-likelihood per state of each observation\n def _emission_logl(self):\n \"\"\"\n arguments: (self, X)\n return: logframe\n \"\"\"\n pass # implemented in subclass\n\n # _emission_pre_mstep: prepare m-step for emission parameters\n def _emission_pre_mstep(self):\n \"\"\"\n arguments: (self, gamma, emission_var)\n return: None\n > process gamma and save output to emission_var\n \"\"\"\n pass # implemented in subclass\n\n # _emission_mstep: perform m-step for emission parameters\n def _emission_mstep(self):\n \"\"\"\n arguments: (self, X, emission_var)\n return: None\n > compute the emission parameters\n \"\"\"\n pass # implemented in subclass\n\n # _state_sample: generate observation for given state\n def _state_sample(self):\n \"\"\"\n arguments: (self, state, random_state=None)\n return: np.ndarray of length equal to dimension of observation\n > generate sample from state\n \"\"\"\n pass # implemented in subclass\n\n # sample: generate random observation series\n def sample(self, n_samples=5, left_censor=0, right_censor=1, random_state=None):\n self._init(None) # see \"note for programmers\" in init() in GaussianHSMM\n self._check()\n # setup random state\n if random_state is None:\n random_state = self.random_state\n rnd_checked = np.random.default_rng(random_state)\n # adapted from hmmlearn 0.2.3 (see _BaseHMM.score function)\n pi_cdf = np.cumsum(self.pi)\n tmat_cdf = np.cumsum(self.tmat, axis=1)\n dur_cdf = np.cumsum(self._dur_probmat(), axis=1)\n # for first state\n currstate = (pi_cdf > rnd_checked.random()).argmax() # argmax() returns only the first occurrence\n currdur = (dur_cdf[currstate] > rnd_checked.random()).argmax() + 1\n if left_censor != 0:\n currdur -= rnd_checked.integers(low=0, high=currdur) # if with left censor, remove some of X\n if right_censor == 0 and currdur > n_samples:\n print(\"SAMPLE: n_samples is too small to contain the first state duration.\")\n return None\n state_sequence = [currstate] * currdur\n X = [self._state_sample(currstate, rnd_checked) for i in range(currdur)] # generate observation\n ctr_sample = currdur\n # for next state transitions\n while ctr_sample < n_samples:\n currstate = (tmat_cdf[currstate] > rnd_checked.random()).argmax()\n currdur = (dur_cdf[currstate] > rnd_checked.random()).argmax() + 1\n # test if now in the end of generating samples\n if ctr_sample + currdur > n_samples:\n if right_censor != 0:\n currdur = n_samples - ctr_sample # if with right censor, cap the samples to n_samples\n else:\n break # else, do not include exceeding state duration\n state_sequence += [currstate] * currdur\n X += [self._state_sample(currstate, rnd_checked) for i in range(currdur)] # generate observation\n ctr_sample += currdur\n return ctr_sample, np.atleast_2d(X), np.array(state_sequence, dtype=int)\n\n # _core_u_only: container for core._u_only (for multiple observation sequences)\n def _core_u_only(self, logframe):\n n_samples = logframe.shape[0]\n u = np.empty((n_samples, self.n_states, self.n_durations))\n core._u_only(n_samples, self.n_states, self.n_durations,\n logframe, u)\n return u\n\n # _core_forward: container for core._forward (for multiple observation sequences)\n def _core_forward(self, u, logdur, left_censor, right_censor):\n n_samples = u.shape[0]\n if right_censor != 0:\n eta_samples = n_samples + self.n_durations - 1\n else:\n eta_samples = n_samples\n eta = np.empty((eta_samples + 1, self.n_states, self.n_durations)) # +1\n xi = np.empty((n_samples + 1, self.n_states, self.n_states)) # +1\n core._forward(n_samples, self.n_states, self.n_durations,\n log_mask_zero(self.pi),\n log_mask_zero(self.tmat),\n logdur, left_censor, right_censor, eta, u, xi)\n return eta, xi\n\n # _core_backward: container for core._backward (for multiple observation sequences)\n def _core_backward(self, u, logdur, right_censor):\n n_samples = u.shape[0]\n beta = np.empty((n_samples, self.n_states))\n betastar = np.empty((n_samples, self.n_states))\n core._backward(n_samples, self.n_states, self.n_durations,\n log_mask_zero(self.pi),\n log_mask_zero(self.tmat),\n logdur, right_censor, beta, u, betastar)\n return beta, betastar\n\n # _core_smoothed: container for core._smoothed (for multiple observation sequences)\n def _core_smoothed(self, beta, betastar, right_censor, eta, xi):\n n_samples = beta.shape[0]\n gamma = np.empty((n_samples, self.n_states))\n core._smoothed(n_samples, self.n_states, self.n_durations,\n beta, betastar, right_censor, eta, xi, gamma)\n return gamma\n\n # _core_viterbi: container for core._viterbi (for multiple observation sequences)\n def _core_viterbi(self, u, logdur, left_censor, right_censor):\n n_samples = u.shape[0]\n state_sequence, state_logl = core._viterbi(n_samples, self.n_states, self.n_durations,\n log_mask_zero(self.pi),\n log_mask_zero(self.tmat),\n logdur, left_censor, right_censor, u)\n return state_sequence, state_logl\n\n # score: log-likelihood computation from observation series\n def score(self, X, lengths=None, left_censor=0, right_censor=1):\n X = check_array(X)\n self._init(X)\n self._check()\n logdur = log_mask_zero(self._dur_probmat()) # build logdur\n # main computations\n score = 0\n for i, j in iter_from_X_lengths(X, lengths):\n logframe = self._emission_logl(X[i:j]) # build logframe\n u = self._core_u_only(logframe)\n if left_censor != 0:\n eta, xi = self._core_forward(u, logdur, left_censor, right_censor)\n beta, betastar = self._core_backward(u, logdur, right_censor)\n gamma = self._core_smoothed(beta, betastar, right_censor, eta, xi)\n score += logsumexp(gamma[0, :])\n else: # if without left censor, computation can be simplified\n _, betastar = self._core_backward(u, logdur, right_censor)\n gammazero = log_mask_zero(self.pi) + betastar[0]\n score += logsumexp(gammazero)\n return score\n\n # predict: hidden state & duration estimation from observation series\n def predict(self, X, lengths=None, left_censor=0, right_censor=1):\n X = check_array(X)\n self._init(X)\n self._check()\n logdur = log_mask_zero(self._dur_probmat()) # build logdur\n # main computations\n state_logl = 0 # math note: this is different from score() output\n state_sequence = np.empty(X.shape[0], dtype=int) # total n_samples = X.shape[0]\n for i, j in iter_from_X_lengths(X, lengths):\n logframe = self._emission_logl(X[i:j]) # build logframe\n u = self._core_u_only(logframe)\n iter_state_sequence, iter_state_logl = self._core_viterbi(u, logdur, left_censor, right_censor)\n state_logl += iter_state_logl\n state_sequence[i:j] = iter_state_sequence\n return state_sequence, state_logl\n\n # fit: parameter estimation from observation series\n def fit(self, X, lengths=None, left_censor=0, right_censor=1):\n X = check_array(X)\n self._init(X)\n self._check()\n # main computations\n for itera in range(self.n_iter):\n score = 0\n pi_num = np.full(self.n_states, -np.inf)\n tmat_num = dur_num = -np.inf\n emission_var = np.empty((X.shape[0], self.n_states)) # cumulative concatenation of gammas\n logdur = log_mask_zero(self._dur_probmat()) # build logdur\n for i, j in iter_from_X_lengths(X, lengths):\n logframe = self._emission_logl(X[i:j]) # build logframe\n u = self._core_u_only(logframe)\n eta, xi = self._core_forward(u, logdur, left_censor, right_censor)\n beta, betastar = self._core_backward(u, logdur, right_censor)\n gamma = self._core_smoothed(beta, betastar, right_censor, eta, xi)\n score += logsumexp(gamma[0, :]) # this is the output of score()\n # preparation for reestimation / M-step\n if eta.shape[0] != j - i + 1:\n eta = eta[:j - i + 1]\n xi[j - i] = tmat_num\n eta[j - i] = dur_num\n pi_num = logsumexp([pi_num, gamma[0]], axis=0)\n tmat_num = logsumexp(xi, axis=0)\n dur_num = logsumexp(eta, axis=0)\n emission_var[i:j] = gamma\n # check for loop break\n if itera > 0 and (score - old_score) < self.tol:\n print(\"FIT: converged at loop {}.\".format(itera + 1))\n break\n else:\n old_score = score\n # reestimation / M-step\n self.pi = np.exp(pi_num - logsumexp(pi_num))\n self.tmat = np.exp(tmat_num - logsumexp(tmat_num, axis=1)[None].T)\n new_dur = np.exp(dur_num - logsumexp(dur_num, axis=1)[None].T)\n self._dur_mstep(new_dur) # new durations\n self._emission_mstep(X, emission_var) # new emissions\n print(\"FIT: reestimation complete for loop {}.\".format(itera + 1))\n\n\n# Sample Subclass: Explicit Duration HSMM with Gaussian Emissions\nclass GaussianHSMM(HSMM):\n def __init__(self, n_states=2, n_durations=5, n_iter=20, tol=1e-2, random_state=None):\n super().__init__(n_states, n_durations, n_iter, tol, random_state)\n\n def _init(self, X):\n super()._init()\n # note for programmers: for every attribute that needs X in score()/predict()/fit(),\n # there must be a condition \"if X is None\" because sample() doesn't need an X, but\n # default attribute values must be initiated for sample() to proceed.\n if not hasattr(self, \"mean\"): # also set self.n_dim here\n if X is None: # default for sample()\n self.n_dim = 1\n self.mean = np.arange(0., self.n_states)[:, None] # = [[0.], [1.], [2.], ...]\n else:\n self.n_dim = X.shape[1]\n kmeans = cluster.KMeans(n_clusters=self.n_states, random_state=self.random_state)\n kmeans.fit(X)\n self.mean = kmeans.cluster_centers_\n else:\n self.n_dim = self.mean.shape[1] # also default for sample()\n if not hasattr(self, \"covmat\"):\n if X is None: # default for sample()\n self.covmat = np.repeat(np.identity(self.n_dim)[None], self.n_states, axis=0)\n else:\n # TODO: initial covariance matrices must be computed from X\n self.covmat = np.repeat(np.identity(self.n_dim)[None], self.n_states, axis=0)\n\n def _check(self):\n super()._check()\n # means\n self.mean = np.asarray(self.mean)\n if self.mean.shape != (self.n_states, self.n_dim):\n raise ValueError(\"means (self.mean) must have shape ({}, {})\"\n .format(self.n_states, self.n_dim))\n # covariance matrices\n self.covmat = np.asarray(self.covmat)\n if self.covmat.shape != (self.n_states, self.n_dim, self.n_dim):\n raise ValueError(\"covariance matrices (self.covmat) must have shape ({0}, {1}, {1})\"\n .format(self.n_states, self.n_dim))\n\n def _dur_init(self):\n # non-parametric duration\n if not hasattr(self, \"dur\"):\n self.dur = np.full((self.n_states, self.n_durations), 1.0 / self.n_durations)\n\n def _dur_check(self):\n self.dur = np.asarray(self.dur)\n if self.dur.shape != (self.n_states, self.n_durations):\n raise ValueError(\"duration probabilities (self.dur) must have shape ({}, {})\"\n .format(self.n_states, self.n_durations))\n if not np.allclose(self.dur.sum(axis=1), 1.0):\n raise ValueError(\"duration probabilities (self.dur) must add up to 1.0\")\n\n def _dur_probmat(self):\n # non-parametric duration\n return self.dur\n\n def _dur_mstep(self, new_dur):\n # non-parametric duration\n self.dur = new_dur\n\n def _emission_logl(self, X):\n # abort EM loop if any covariance matrix is not symmetric, positive-definite.\n # adapted from hmmlearn 0.2.3 (see _utils._validate_covars function)\n for n, cv in enumerate(self.covmat):\n if (not np.allclose(cv, cv.T) or np.any(np.linalg.eigvalsh(cv) <= 0)):\n raise ValueError(\"component {} of covariance matrix is not symmetric, positive-definite.\"\n .format(n))\n # https://www.youtube.com/watch?v=tWoFaPwbzqE&t=1694s\n n_samples = X.shape[0]\n logframe = np.empty((n_samples, self.n_states))\n for i in range(self.n_states):\n # math note: since Gaussian distribution is continuous, probability density\n # is what's computed here. thus log-likelihood can be positive!\n multigauss = multivariate_normal(self.mean[i], self.covmat[i])\n for j in range(n_samples):\n logframe[j, i] = log_mask_zero(multigauss.pdf(X[j]))\n return logframe\n\n def _emission_mstep(self, X, emission_var):\n denominator = logsumexp(emission_var, axis=0)\n weight_normalized = np.exp(emission_var - denominator)[None].T\n # compute means (from definition; weighted)\n self.mean = (weight_normalized * X).sum(1)\n # compute covariance matrices (from definition; weighted)\n dist = X - self.mean[:, None]\n self.covmat = ((dist * weight_normalized)[:, :, :, None] * dist[:, :, None]).sum(1)\n\n def _state_sample(self, state, random_state=None):\n rnd_checked = np.random.default_rng(random_state)\n return rnd_checked.multivariate_normal(self.mean[state], self.covmat[state])" ]
[ [ "numpy.full", "numpy.array", "scipy.special.logsumexp", "numpy.empty", "numpy.asarray", "sklearn.cluster.KMeans", "numpy.random.default_rng", "numpy.exp", "numpy.identity", "numpy.allclose", "scipy.stats.multivariate_normal", "numpy.arange", "numpy.linalg.eigvalsh", "numpy.cumsum", "sklearn.utils.check_array", "numpy.atleast_2d" ] ]
vossenwout/gtadeepproblog
[ "56bcf5208e79c17510b5d288068fabc6cd64f3cf" ]
[ "src/deepproblog/utils/confusion_matrix.py" ]
[ "from typing import List, Union\n\nimport numpy as np\n\nfrom deepproblog.utils import TabularFormatter\n\n\nclass ConfusionMatrix(object):\n def __init__(self, classes: Union[int, List[str]] = 0):\n if isinstance(classes, int):\n self.n = classes\n self.classes = list(range(self.n))\n else:\n self.classes = classes\n self.n = len(classes)\n self.matrix = np.zeros((self.n, self.n), dtype=np.uint)\n\n def get_index(self, c):\n if c not in self.classes:\n self.grow(c)\n return self.classes.index(c)\n\n def grow(self, c):\n self.classes.append(c)\n self.n = len(self.classes)\n new_matrix = np.zeros((self.n, self.n), dtype=np.uint)\n new_matrix[0 : self.n - 1, 0 : self.n - 1] = self.matrix\n self.matrix = new_matrix\n\n def add_item(self, predicted, actual):\n actual_i = self.get_index(actual)\n predicted_i = self.get_index(predicted)\n\n self.matrix[predicted_i, actual_i] += 1\n\n def __str__(self):\n formatter = TabularFormatter()\n data = [[\"\"] * (self.n + 2), [\"\", \"\"] + self.classes]\n data[0][(self.n + 1) // 2 + 1] = \"Actual\"\n for row in range(self.n):\n data.append(\n [\" \", self.classes[row]]\n + [str(self.matrix[row, col]) for col in range(self.n)]\n )\n data[len(data) // 2][0] = \"Predicted\"\n return formatter.format(data)\n\n def accuracy(self):\n correct = 0\n for i in range(self.n):\n correct += self.matrix[i, i]\n total = self.matrix.sum()\n acc = correct / total\n print(\"Accuracy: \", acc)\n return acc\n" ]
[ [ "numpy.zeros" ] ]
wrrobin/Kernels
[ "c8f4b2054c649b176d737647671e227bcfb19da6" ]
[ "PYTHON/stencil-numba.py" ]
[ "#!/usr/bin/env python3\n#\n# Copyright (c) 2015, Intel Corporation\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided\n# with the distribution.\n# * Neither the name of Intel Corporation nor the names of its\n# contributors may be used to endorse or promote products\n# derived from this software without specific prior written\n# permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n#\n# *******************************************************************\n#\n# NAME: Stencil\n#\n# PURPOSE: This program tests the efficiency with which a space-invariant,\n# linear, symmetric filter (stencil) can be applied to a square\n# grid or image.\n#\n# USAGE: The program takes as input the linear\n# dimension of the grid, and the number of iterations on the grid\n#\n# <progname> <iterations> <grid size>\n#\n# The output consists of diagnostics to make sure the\n# algorithm worked, and of timing statistics.\n#\n# HISTORY: - Written by Rob Van der Wijngaart, February 2009.\n# - RvdW: Removed unrolling pragmas for clarity;\n# added constant to array \"in\" at end of each iteration to force\n# refreshing of neighbor data in parallel versions; August 2013\n# - Converted to Python by Jeff Hammond, February 2016.\n#\n# *******************************************************************\n\nimport sys\nprint('Python version = ', str(sys.version_info.major)+'.'+str(sys.version_info.minor))\nif sys.version_info >= (3, 3):\n from time import process_time as timer\nelse:\n from timeit import default_timer as timer\nfrom numba import jit\nimport numpy\nprint('Numpy version = ', numpy.version.version)\n\n@jit\ndef grid(n,r,W,A,B):\n if r>0:\n b = n-r\n for s in range(-r, r+1):\n for t in range(-r, r+1):\n B[r:b,r:b] += W[r+t,r+s] * A[r+t:b+t,r+s:b+s]\n\n@jit\ndef star2(n,W,A,B):\n B[2:n-2,2:n-2] += W[2,2] * A[2:n-2,2:n-2] \\\n + W[2,0] * A[2:n-2,0:n-4] \\\n + W[2,1] * A[2:n-2,1:n-3] \\\n + W[2,3] * A[2:n-2,3:n-1] \\\n + W[2,4] * A[2:n-2,4:n-0] \\\n + W[0,2] * A[0:n-4,2:n-2] \\\n + W[1,2] * A[1:n-3,2:n-2] \\\n + W[3,2] * A[3:n-1,2:n-2] \\\n + W[4,2] * A[4:n-0,2:n-2]\n\n@jit\ndef star(n,r,W,A,B):\n b = n-r\n B[r:b,r:b] += W[r,r] * A[r:b,r:b]\n for s in range(1,r+1):\n B[r:b,r:b] += W[r,r-s] * A[r:b,r-s:b-s] \\\n + W[r,r+s] * A[r:b,r+s:b+s] \\\n + W[r-s,r] * A[r-s:b-s,r:b] \\\n + W[r+s,r] * A[r+s:b+s,r:b]\n\ndef main():\n\n # ********************************************************************\n # read and test input parameters\n # ********************************************************************\n\n print('Parallel Research Kernels version ') #, PRKVERSION\n print('Python stencil execution on 2D grid')\n\n if len(sys.argv) < 3:\n print('argument count = ', len(sys.argv))\n sys.exit(\"Usage: ./stencil <# iterations> <array dimension> [<star/grid> <radius>]\")\n\n iterations = int(sys.argv[1])\n if iterations < 1:\n sys.exit(\"ERROR: iterations must be >= 1\")\n\n n = int(sys.argv[2])\n if n < 1:\n sys.exit(\"ERROR: array dimension must be >= 1\")\n\n if len(sys.argv) > 3:\n pattern = sys.argv[3]\n else:\n pattern = 'star'\n\n if len(sys.argv) > 4:\n r = int(sys.argv[4])\n if r < 1:\n sys.exit(\"ERROR: Stencil radius should be positive\")\n if (2*r+1) > n:\n sys.exit(\"ERROR: Stencil radius exceeds grid size\")\n else:\n r = 2 # radius=2 is what other impls use right now\n\n print('Grid size = ', n)\n print('Radius of stencil = ', r)\n if pattern == 'star':\n print('Type of stencil = ','star')\n else:\n print('Type of stencil = ','grid')\n\n print('Data type = double precision')\n print('Compact representation of stencil loop body')\n print('Number of iterations = ', iterations)\n\n # there is certainly a more Pythonic way to initialize W,\n # but it will have no impact on performance.\n W = numpy.zeros(((2*r+1),(2*r+1)))\n if pattern == 'star':\n stencil_size = 4*r+1\n for i in range(1,r+1):\n W[r,r+i] = +1./(2*i*r)\n W[r+i,r] = +1./(2*i*r)\n W[r,r-i] = -1./(2*i*r)\n W[r-i,r] = -1./(2*i*r)\n\n else:\n stencil_size = (2*r+1)**2\n for j in range(1,r+1):\n for i in range(-j+1,j):\n W[r+i,r+j] = +1./(4*j*(2*j-1)*r)\n W[r+i,r-j] = -1./(4*j*(2*j-1)*r)\n W[r+j,r+i] = +1./(4*j*(2*j-1)*r)\n W[r-j,r+i] = -1./(4*j*(2*j-1)*r)\n\n W[r+j,r+j] = +1./(4*j*r)\n W[r-j,r-j] = -1./(4*j*r)\n\n A = numpy.fromfunction(lambda i,j: i+j, (n,n), dtype=float)\n B = numpy.zeros((n,n))\n\n for k in range(iterations+1):\n # start timer after a warmup iteration\n if k<1: t0 = timer()\n\n if pattern == 'star':\n if r == 2:\n star2(n,W,A,B)\n else:\n star(n,r,W,A,B)\n\n else: # grid\n grid(n,r,W,A,B)\n A += 1.0\n\n t1 = timer()\n stencil_time = t1 - t0\n\n #******************************************************************************\n #* Analyze and output results.\n #******************************************************************************\n\n norm = numpy.linalg.norm(numpy.reshape(B,n*n),ord=1)\n active_points = (n-2*r)**2\n norm /= active_points\n\n epsilon=1.e-8\n\n # verify correctness\n reference_norm = 2*(iterations+1)\n if abs(norm-reference_norm) < epsilon:\n print('Solution validates')\n flops = (2*stencil_size+1) * active_points\n avgtime = stencil_time/iterations\n print('Rate (MFlops/s): ',1.e-6*flops/avgtime, ' Avg time (s): ',avgtime)\n else:\n print('ERROR: L1 norm = ', norm,' Reference L1 norm = ', reference_norm)\n sys.exit()\n\n\nif __name__ == '__main__':\n main()\n\n" ]
[ [ "numpy.reshape", "numpy.fromfunction", "numpy.zeros" ] ]
MLJejuCamp2017/MAD-GAN-MLCAMP
[ "0615e4acd7f8488abc58f62985e400373b62b5d1" ]
[ "src/main_working.py" ]
[ "import os\nimport scipy.misc\nimport numpy as np\n\nfrom model import MADGAN\nfrom utils import pp, visualize, to_json, show_all_variables\n\nimport tensorflow as tf\n\nflags = tf.app.flags\nflags.DEFINE_integer(\"epoch\", 25, \"Epoch to train [25]\")\nflags.DEFINE_float(\"learning_rate\", 0.0002, \"Learning rate of for adam [0.0002]\")\nflags.DEFINE_float(\"beta1\", 0.5, \"Momentum term of adam [0.5]\")\nflags.DEFINE_integer(\"train_size\", np.inf, \"The size of train images [np.inf]\")\nflags.DEFINE_integer(\"batch_size\", 64, \"The size of batch images [64]\")\nflags.DEFINE_integer(\"input_height\", 128, \"The size of image to use (will be center cropped). [108]\")\nflags.DEFINE_integer(\"input_width\", None, \"The size of image to use (will be center cropped). If None, same value as input_height [None]\")\nflags.DEFINE_integer(\"output_height\", 128, \"The size of the output images to produce [64]\")\nflags.DEFINE_integer(\"output_width\", None, \"The size of the output images to produce. If None, same value as output_height [None]\")\nflags.DEFINE_string(\"dataset\", \"celebA\", \"The name of dataset [celebA, mnist, lsun]\")\nflags.DEFINE_string(\"input_fname_pattern\", \"*.jpg\", \"Glob pattern of filename of input images [*]\")\nflags.DEFINE_string(\"checkpoint_dir\", \"checkpoint\", \"Directory name to save the checkpoints [checkpoint]\")\nflags.DEFINE_string(\"sample_dir\", \"samples\", \"Directory name to save the image samples [samples]\")\nflags.DEFINE_boolean(\"train\", False, \"True for training, False for testing [False]\")\nflags.DEFINE_boolean(\"crop\", False, \"True for training, False for testing [False]\")\nflags.DEFINE_boolean(\"visualize\", False, \"True for visualizing, False for nothing [False]\")\nflags.DEFINE_integer(\"num_generat\", 5, \"Number of generators. [5]\")\n\nFLAGS = flags.FLAGS\n\ndef main(_):\n pp.pprint(flags.FLAGS.__flags)\n\n if FLAGS.input_width is None:\n FLAGS.input_width = FLAGS.input_height\n if FLAGS.output_width is None:\n FLAGS.output_width = FLAGS.output_height\n\n if not os.path.exists(FLAGS.checkpoint_dir):\n os.makedirs(FLAGS.checkpoint_dir)\n if not os.path.exists(FLAGS.sample_dir):\n os.makedirs(FLAGS.sample_dir)\n\n #gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.333)\n run_config = tf.ConfigProto()\n run_config.gpu_options.allow_growth=True\n\n with tf.Session(config=run_config) as sess:\n if FLAGS.dataset == 'mnist':\n madgan = MADGAN(\n sess,\n input_width=FLAGS.input_width,\n input_height=FLAGS.input_height,\n output_width=FLAGS.output_width,\n output_height=FLAGS.output_height,\n batch_size=FLAGS.batch_size,\n sample_num=FLAGS.batch_size,\n y_dim=10,\n dataset_name=FLAGS.dataset,\n input_fname_pattern=FLAGS.input_fname_pattern,\n crop=FLAGS.crop,\n checkpoint_dir=FLAGS.checkpoint_dir,\n num_generat = FLAGS.num_generat,\n sample_dir=FLAGS.sample_dir)\n else:\n madgan = MADGAN(\n sess,\n input_width=FLAGS.input_width,\n input_height=FLAGS.input_height,\n output_width=FLAGS.output_width,\n output_height=FLAGS.output_height,\n batch_size=FLAGS.batch_size,\n sample_num=FLAGS.batch_size,\n dataset_name=FLAGS.dataset,\n input_fname_pattern=FLAGS.input_fname_pattern,\n crop=FLAGS.crop,\n checkpoint_dir=FLAGS.checkpoint_dir,\n num_generat = FLAGS.num_generat,\n sample_dir=FLAGS.sample_dir)\n\n show_all_variables()\n\n if FLAGS.train:\n madgan.train(FLAGS)\n else:\n if not madgan.load(FLAGS.checkpoint_dir)[0]:\n raise Exception(\"[!] Train a model first, then run test mode\")\n \n\n # to_json(\"./web/js/layers.js\", [dcgan.h0_w, dcgan.h0_b, dcgan.g_bn0],\n # [dcgan.h1_w, dcgan.h1_b, dcgan.g_bn1],\n # [dcgan.h2_w, dcgan.h2_b, dcgan.g_bn2],\n # [dcgan.h3_w, dcgan.h3_b, dcgan.g_bn3],\n # [dcgan.h4_w, dcgan.h4_b, None])\n\n # Below is codes for visualization\n OPTION = 1\n # visualize(sess, dcgan, FLAGS, OPTION)\n\nif __name__ == '__main__':\n tf.app.run()" ]
[ [ "tensorflow.ConfigProto", "tensorflow.app.run", "tensorflow.Session" ] ]
krickwix/ncsdk
[ "c3714ed607d3a4c6612668428765fea82efee166" ]
[ "examples/caffe/GoogLeNet/run.py" ]
[ "#! /usr/bin/env python3\n\n# Copyright (c) 2017-2018 Intel 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\nfrom mvnc import mvncapi as mvnc\nimport sys\nimport numpy\nimport cv2\nimport time\nimport csv\nimport os\nimport sys\n\ndim=(224,224)\nEXAMPLES_BASE_DIR='../../'\n\n# ***************************************************************\n# get labels\n# ***************************************************************\nlabels_file=EXAMPLES_BASE_DIR+'data/ilsvrc12/synset_words.txt'\nlabels=numpy.loadtxt(labels_file,str,delimiter='\\t')\n\n# ***************************************************************\n# configure the NCS\n# ***************************************************************\nmvnc.SetGlobalOption(mvnc.GlobalOption.LOG_LEVEL, 2)\n\n# ***************************************************************\n# Get a list of ALL the sticks that are plugged in\n# ***************************************************************\ndevices = mvnc.EnumerateDevices()\nif len(devices) == 0:\n\tprint('No devices found')\n\tquit()\n\n# ***************************************************************\n# Pick the first stick to run the network\n# ***************************************************************\ndevice = mvnc.Device(devices[0])\n\n# ***************************************************************\n# Open the NCS\n# ***************************************************************\ndevice.OpenDevice()\n\nnetwork_blob='graph'\n\n#Load blob\nwith open(network_blob, mode='rb') as f:\n\tblob = f.read()\n\ngraph = device.AllocateGraph(blob)\n\n# ***************************************************************\n# Load the image\n# ***************************************************************\nilsvrc_mean = numpy.load(EXAMPLES_BASE_DIR+'data/ilsvrc12/ilsvrc_2012_mean.npy').mean(1).mean(1) #loading the mean file\nimg = cv2.imread(EXAMPLES_BASE_DIR+'data/images/nps_electric_guitar.png')\nimg=cv2.resize(img,dim)\nimg = img.astype(numpy.float32)\nimg[:,:,0] = (img[:,:,0] - ilsvrc_mean[0])\nimg[:,:,1] = (img[:,:,1] - ilsvrc_mean[1])\nimg[:,:,2] = (img[:,:,2] - ilsvrc_mean[2])\n\n# ***************************************************************\n# Send the image to the NCS\n# ***************************************************************\ngraph.LoadTensor(img.astype(numpy.float16), 'user object')\n\n# ***************************************************************\n# Get the result from the NCS\n# ***************************************************************\noutput, userobj = graph.GetResult()\n\n# ***************************************************************\n# Print the results of the inference form the NCS\n# ***************************************************************\norder = output.argsort()[::-1][:6]\nprint('\\n------- predictions --------')\nfor i in range(0,5):\n\tprint ('prediction ' + str(i) + ' (probability ' + str(output[order[i]]) + ') is ' + labels[order[i]] + ' label index is: ' + str(order[i]) )\n\n\n# ***************************************************************\n# Clean up the graph and the device\n# ***************************************************************\ngraph.DeallocateGraph()\ndevice.CloseDevice()\n \n\n\n\n" ]
[ [ "numpy.loadtxt", "numpy.load" ] ]
cy-TOHACKS21/GoGoMeet-
[ "94d785ed388a955e987c0acda8332e0035010074" ]
[ "Cogs/meet.py" ]
[ "import discord\r\nimport asyncio\r\nimport datetime\r\nfrom discord.ext import commands\r\nimport os\r\nimport requests\r\nimport json\r\nimport pandas as pd\r\nimport re\r\nfrom datetime import datetime, timedelta\r\n\r\n\r\n# Retrieving Distance Matrix API key\r\nfin = open('Saved/Keys.txt')\r\nlines = list(map(lambda x: x.strip(), fin.readlines()))\r\nfin.close()\r\n\r\nAPI_KEY = lines[3]\r\n\r\n\r\nclass Meet_Cog(commands.Cog):\r\n\r\n def __init__(self, bot):\r\n self.bot = bot\r\n\r\n @commands.Cog.listener()\r\n async def on_ready(self):\r\n print('Meet: Online')\r\n\r\n @commands.command(aliases = ['gogomeet'])\r\n async def meet(self, ctx):\r\n\r\n # Basic wait_for message check\r\n def check(answer: discord.Message): \r\n return answer.channel == ctx.channel and answer.author.id == ctx.author.id\r\n\r\n # Prompt user for origin locations\r\n origin_message = await ctx.send('**Enter origin locations (separate by |): **')\r\n try:\r\n origin_wait = await self.bot.wait_for('message', timeout = 180, check = check)\r\n origin = origin_wait.content.replace(' ', '+').split('|')\r\n origin = '|'.join(list(map(lambda x: x.strip(), origin)))\r\n await origin_wait.delete()\r\n await origin_message.delete()\r\n except asyncio.TimeoutError:\r\n await origin_message.delete()\r\n await ctx.send('Timed out.')\r\n return\r\n\r\n # Prompt user for destination location\r\n destination_message = await ctx.send('**Enter destination location: **')\r\n try:\r\n destination_wait = await self.bot.wait_for('message', timeout = 180, check = check)\r\n destination = destination_wait.content.replace(' ', '+')\r\n await destination_wait.delete()\r\n await destination_message.delete()\r\n except asyncio.TimeoutError:\r\n await destination_message.delete()\r\n await ctx.send('Timed out.')\r\n return\r\n\r\n # Prompt user for arrival time\r\n arrival_message = await ctx.send('**Enter arrival time (YYYY-MM-DD HH:MM:SS): **')\r\n try:\r\n arrival_wait = await self.bot.wait_for('message', timeout = 180, check = check)\r\n arrival_time = arrival_wait.content\r\n arrival_time = datetime.strptime(arrival_time, '%Y-%m-%d %H:%M:%S')\r\n await arrival_wait.delete()\r\n await arrival_message.delete()\r\n except asyncio.TimeoutError:\r\n await arrival_message.delete()\r\n await ctx.send('Timed out.')\r\n return\r\n\r\n # Get current time\r\n current_time = datetime.now().replace(microsecond = 0)\r\n \r\n # API call using given parameters\r\n url = f'https://maps.googleapis.com/maps/api/distancematrix/json?origins={origin}&destinations={destination}&key={API_KEY}'\r\n request = requests.get(url)\r\n result = json.loads(request.text)\r\n\r\n # Retrieve full addresses for origins and destination\r\n origin_addresses = result['origin_addresses']\r\n dest_address = result['destination_addresses'][0]\r\n\r\n # Initialize variables for loop\r\n d = {}\r\n day_amount = sec_amount = min_amount = hour_amount = week_amount = 0\r\n count = 0\r\n\r\n # Loop through each origin address\r\n for i in origin_addresses:\r\n # Retrieve distance and duration between origin and destination\r\n distance = result['rows'][count]['elements'][0]['distance']['text']\r\n duration = result['rows'][count]['elements'][0]['duration']['text']\r\n\r\n # Parse string to create timedelta object\r\n time_split = re.findall('[^ ]+ [^ ]+', duration)\r\n for j in time_split:\r\n if 'day' in j:\r\n day_amount = int(j.split()[0])\r\n elif 'sec' in j:\r\n sec_amount = int(j.split()[0])\r\n elif 'min' in j:\r\n min_amount = int(j.split()[0])\r\n elif 'hour' in j:\r\n hour_amount = int(j.split()[0])\r\n elif 'week' in j:\r\n week_amount = int(j.split()[0])\r\n\r\n # Create timedelta object and calculate departure time\r\n time_delta = timedelta(weeks = week_amount, days = day_amount, hours = hour_amount, minutes = min_amount, seconds = sec_amount)\r\n departure_time = arrival_time - time_delta\r\n\r\n if len(i) > 35:\r\n i = i[:35] + '...'\r\n\r\n # Add info to dictionary\r\n d[i] = [distance, duration, departure_time]\r\n count += 1\r\n\r\n # Create dataframe\r\n df = pd.DataFrame(d, index = ['Distance:', 'Duration:', 'Departure Time:'])\r\n\r\n # Creating results embed\r\n embed = discord.Embed(title = 'GoGoMeet!', colour = discord.Colour(0xefe61))\r\n embed.description = 'Meet up with friends without the hassle of waiting!'\r\n embed.set_thumbnail(url = 'https://imgur.com/jVdMcwL.png')\r\n\r\n embed.add_field(name = 'Current Time:', value = current_time, inline = False)\r\n embed.add_field(name = 'Arrival Time:', value = arrival_time, inline = False)\r\n embed.add_field(name = 'Destination:', value = dest_address, inline = False)\r\n\r\n embed.set_footer(text = 'GoGoMeet!', icon_url = 'https://imgur.com/jVdMcwL.png')\r\n embed.timestamp = datetime.utcnow()\r\n\r\n await ctx.send(embed = embed)\r\n await ctx.send(f'```{df}```')\r\n\r\n\r\ndef setup(bot):\r\n bot.add_cog(Meet_Cog(bot))\r\n" ]
[ [ "pandas.DataFrame" ] ]
MasazI/python-r-stan-bayesian-model-2
[ "288876b31b6c3d74d523babc475d4794cd29680a" ]
[ "exec/5-exec-5-7.py" ]
[ "import numpy as np\nimport seaborn as sns\nimport pandas\nimport mcmc_tools\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\n\n# ファイルの読み込み\n# y: 生存していた種子数 応答変数\n# N: 調査した種子数\n# x: 体サイズ\n# f: 処理の違い(CまたはT)\ndata4a = pandas.read_csv('data4a.csv')\nprint(data4a.head())\nprint(data4a.describe())\n\n# ここでは、2項ロジスティック回帰を利用して推定を試みる。\n# 種子の生存率を確立で表すため、ロジスティック関数を利用する。\n# 確率はxとfに依存するものとする。\n# その確率と、調査した種子数を説明変数として、生存していた種子数をモデリングする。\nf_effec = {\n 'C': 0,\n 'T': 1\n}\n\ndata4a_re = data4a.replace(f_effec)\nprint(data4a_re.head())\n\ny = data4a_re['y']\nx = data4a_re['x']\nf = data4a_re['f']\nN = data4a_re['N']\nI = len(y)\n\nstan_data = {\n 'I': I,\n 'y': y,\n 'N': N,\n 'x': x,\n 'f': f\n}\n\n# コンパイル\nfilename = '../model/5-exec-5-7'\nmcmc_result = mcmc_tools.sampling(filename, stan_data, n_jobs=4, seed=1983)\nmcmc_sample = mcmc_result.extract()\n\n\n# 予測値と実測値のプロット\nquantile = [10, 50, 90]\ncolname = ['p' + str(x) for x in quantile]\nprint(np.percentile(mcmc_sample['y_pred'], q=quantile, axis=0))\ndata4a_pred = pandas.DataFrame(np.percentile(mcmc_sample['y_pred'], q=quantile, axis=0).T, columns=colname)\n# 実装値と予測値のDataFrameを作成\nd = pandas.concat([data4a_re, data4a_pred], axis=1)\nd0 = d.query('f==0')\nd1 = d.query('f==1')\n\nplt.errorbar(d0.y, d0.p50, yerr=[d0.p50 - d0.p10, d0.p90 - d0.p50],\n fmt='o', ecolor='gray', ms=10, alpha=0.8, marker='o', mfc='blue', capsize=3, label=\"f=0\")\nplt.errorbar(d1.y, d1.p50, yerr=[d1.p50 - d1.p10, d1.p90 - d1.p50],\n fmt='o', ecolor='gray', ms=10, alpha=0.8, marker='^', mfc='green', capsize=3, label=\"f=1\")\nax = plt.axes()\nplt.plot([0,10], [0,10], 'k--', alpha=0.7)\nax.set_aspect('equal')\nplt.legend()\nplt.xlabel('Observed', fontsize=12)\nplt.ylabel('Predicted', fontsize=12)\nplt.show()\n\n# この結果から、練習問題5(6)よりも5(7)の設定のほうが良い推定を得られることがわかる。\n# これはデータとデータをつなぐ仕組みを考えることにつながる。説明変数はほとんど変わらないのに、\n# 種子が生き残る確率、とと検査した個体数を導入することによって、\n# 推論性能が上昇していることがわかる。\n# これが、スライダークランク機構を例に題して説明される実例である。" ]
[ [ "matplotlib.pyplot.errorbar", "matplotlib.pyplot.xlabel", "numpy.percentile", "matplotlib.pyplot.plot", "matplotlib.pyplot.legend", "matplotlib.pyplot.ylabel", "pandas.concat", "matplotlib.pyplot.show", "pandas.read_csv", "matplotlib.pyplot.axes" ] ]
ziyaointl/scipy
[ "eac43b07eb9681ce52526ce8bc82f0ce2510ce34" ]
[ "scipy/interpolate/tests/test_bsplines.py" ]
[ "from __future__ import division, absolute_import, print_function\n\nimport numpy as np\nfrom numpy.testing import (assert_equal, assert_allclose, assert_,\n suppress_warnings)\nfrom pytest import raises as assert_raises\nimport pytest\n\nfrom scipy.interpolate import (BSpline, BPoly, PPoly, make_interp_spline,\n make_lsq_spline, _bspl, splev, splrep, splprep, splder, splantider,\n sproot, splint, insert)\nimport scipy.linalg as sl\nfrom scipy._lib._version import NumpyVersion\n\nfrom scipy.interpolate._bsplines import _not_a_knot, _augknt\nimport scipy.interpolate._fitpack_impl as _impl\nfrom scipy.interpolate._fitpack import _splint\n\n\nclass TestBSpline(object):\n\n def test_ctor(self):\n # knots should be an ordered 1-D array of finite real numbers\n assert_raises((TypeError, ValueError), BSpline,\n **dict(t=[1, 1.j], c=[1.], k=0))\n with np.errstate(invalid='ignore'):\n assert_raises(ValueError, BSpline, **dict(t=[1, np.nan], c=[1.], k=0))\n assert_raises(ValueError, BSpline, **dict(t=[1, np.inf], c=[1.], k=0))\n assert_raises(ValueError, BSpline, **dict(t=[1, -1], c=[1.], k=0))\n assert_raises(ValueError, BSpline, **dict(t=[[1], [1]], c=[1.], k=0))\n\n # for n+k+1 knots and degree k need at least n coefficients\n assert_raises(ValueError, BSpline, **dict(t=[0, 1, 2], c=[1], k=0))\n assert_raises(ValueError, BSpline,\n **dict(t=[0, 1, 2, 3, 4], c=[1., 1.], k=2))\n\n # non-integer orders\n assert_raises(TypeError, BSpline,\n **dict(t=[0., 0., 1., 2., 3., 4.], c=[1., 1., 1.], k=\"cubic\"))\n assert_raises(TypeError, BSpline,\n **dict(t=[0., 0., 1., 2., 3., 4.], c=[1., 1., 1.], k=2.5))\n\n # basic interval cannot have measure zero (here: [1..1])\n assert_raises(ValueError, BSpline,\n **dict(t=[0., 0, 1, 1, 2, 3], c=[1., 1, 1], k=2))\n\n # tck vs self.tck\n n, k = 11, 3\n t = np.arange(n+k+1)\n c = np.random.random(n)\n b = BSpline(t, c, k)\n\n assert_allclose(t, b.t)\n assert_allclose(c, b.c)\n assert_equal(k, b.k)\n\n def test_tck(self):\n b = _make_random_spline()\n tck = b.tck\n\n assert_allclose(b.t, tck[0], atol=1e-15, rtol=1e-15)\n assert_allclose(b.c, tck[1], atol=1e-15, rtol=1e-15)\n assert_equal(b.k, tck[2])\n\n # b.tck is read-only\n with pytest.raises(AttributeError):\n b.tck = 'foo'\n\n def test_degree_0(self):\n xx = np.linspace(0, 1, 10)\n\n b = BSpline(t=[0, 1], c=[3.], k=0)\n assert_allclose(b(xx), 3)\n\n b = BSpline(t=[0, 0.35, 1], c=[3, 4], k=0)\n assert_allclose(b(xx), np.where(xx < 0.35, 3, 4))\n\n def test_degree_1(self):\n t = [0, 1, 2, 3, 4]\n c = [1, 2, 3]\n k = 1\n b = BSpline(t, c, k)\n\n x = np.linspace(1, 3, 50)\n assert_allclose(c[0]*B_012(x) + c[1]*B_012(x-1) + c[2]*B_012(x-2),\n b(x), atol=1e-14)\n assert_allclose(splev(x, (t, c, k)), b(x), atol=1e-14)\n\n def test_bernstein(self):\n # a special knot vector: Bernstein polynomials\n k = 3\n t = np.asarray([0]*(k+1) + [1]*(k+1))\n c = np.asarray([1., 2., 3., 4.])\n bp = BPoly(c.reshape(-1, 1), [0, 1])\n bspl = BSpline(t, c, k)\n\n xx = np.linspace(-1., 2., 10)\n assert_allclose(bp(xx, extrapolate=True),\n bspl(xx, extrapolate=True), atol=1e-14)\n assert_allclose(splev(xx, (t, c, k)),\n bspl(xx), atol=1e-14)\n\n def test_rndm_naive_eval(self):\n # test random coefficient spline *on the base interval*,\n # t[k] <= x < t[-k-1]\n b = _make_random_spline()\n t, c, k = b.tck\n xx = np.linspace(t[k], t[-k-1], 50)\n y_b = b(xx)\n\n y_n = [_naive_eval(x, t, c, k) for x in xx]\n assert_allclose(y_b, y_n, atol=1e-14)\n\n y_n2 = [_naive_eval_2(x, t, c, k) for x in xx]\n assert_allclose(y_b, y_n2, atol=1e-14)\n\n def test_rndm_splev(self):\n b = _make_random_spline()\n t, c, k = b.tck\n xx = np.linspace(t[k], t[-k-1], 50)\n assert_allclose(b(xx), splev(xx, (t, c, k)), atol=1e-14)\n\n def test_rndm_splrep(self):\n np.random.seed(1234)\n x = np.sort(np.random.random(20))\n y = np.random.random(20)\n\n tck = splrep(x, y)\n b = BSpline(*tck)\n\n t, k = b.t, b.k\n xx = np.linspace(t[k], t[-k-1], 80)\n assert_allclose(b(xx), splev(xx, tck), atol=1e-14)\n\n def test_rndm_unity(self):\n b = _make_random_spline()\n b.c = np.ones_like(b.c)\n xx = np.linspace(b.t[b.k], b.t[-b.k-1], 100)\n assert_allclose(b(xx), 1.)\n\n def test_vectorization(self):\n n, k = 22, 3\n t = np.sort(np.random.random(n))\n c = np.random.random(size=(n, 6, 7))\n b = BSpline(t, c, k)\n tm, tp = t[k], t[-k-1]\n xx = tm + (tp - tm) * np.random.random((3, 4, 5))\n assert_equal(b(xx).shape, (3, 4, 5, 6, 7))\n\n def test_len_c(self):\n # for n+k+1 knots, only first n coefs are used.\n # and BTW this is consistent with FITPACK\n n, k = 33, 3\n t = np.sort(np.random.random(n+k+1))\n c = np.random.random(n)\n\n # pad coefficients with random garbage\n c_pad = np.r_[c, np.random.random(k+1)]\n\n b, b_pad = BSpline(t, c, k), BSpline(t, c_pad, k)\n\n dt = t[-1] - t[0]\n xx = np.linspace(t[0] - dt, t[-1] + dt, 50)\n assert_allclose(b(xx), b_pad(xx), atol=1e-14)\n assert_allclose(b(xx), splev(xx, (t, c, k)), atol=1e-14)\n assert_allclose(b(xx), splev(xx, (t, c_pad, k)), atol=1e-14)\n\n def test_endpoints(self):\n # base interval is closed\n b = _make_random_spline()\n t, _, k = b.tck\n tm, tp = t[k], t[-k-1]\n for extrap in (True, False):\n assert_allclose(b([tm, tp], extrap),\n b([tm + 1e-10, tp - 1e-10], extrap), atol=1e-9)\n\n def test_continuity(self):\n # assert continuity at internal knots\n b = _make_random_spline()\n t, _, k = b.tck\n assert_allclose(b(t[k+1:-k-1] - 1e-10), b(t[k+1:-k-1] + 1e-10),\n atol=1e-9)\n\n def test_extrap(self):\n b = _make_random_spline()\n t, c, k = b.tck\n dt = t[-1] - t[0]\n xx = np.linspace(t[k] - dt, t[-k-1] + dt, 50)\n mask = (t[k] < xx) & (xx < t[-k-1])\n\n # extrap has no effect within the base interval\n assert_allclose(b(xx[mask], extrapolate=True),\n b(xx[mask], extrapolate=False))\n\n # extrapolated values agree with FITPACK\n assert_allclose(b(xx, extrapolate=True),\n splev(xx, (t, c, k), ext=0))\n\n def test_default_extrap(self):\n # BSpline defaults to extrapolate=True\n b = _make_random_spline()\n t, _, k = b.tck\n xx = [t[0] - 1, t[-1] + 1]\n yy = b(xx)\n assert_(not np.all(np.isnan(yy)))\n\n def test_periodic_extrap(self):\n np.random.seed(1234)\n t = np.sort(np.random.random(8))\n c = np.random.random(4)\n k = 3\n b = BSpline(t, c, k, extrapolate='periodic')\n n = t.size - (k + 1)\n\n dt = t[-1] - t[0]\n xx = np.linspace(t[k] - dt, t[n] + dt, 50)\n xy = t[k] + (xx - t[k]) % (t[n] - t[k])\n assert_allclose(b(xx), splev(xy, (t, c, k)))\n\n # Direct check\n xx = [-1, 0, 0.5, 1]\n xy = t[k] + (xx - t[k]) % (t[n] - t[k])\n assert_equal(b(xx, extrapolate='periodic'), b(xy, extrapolate=True))\n\n def test_ppoly(self):\n b = _make_random_spline()\n t, c, k = b.tck\n pp = PPoly.from_spline((t, c, k))\n\n xx = np.linspace(t[k], t[-k], 100)\n assert_allclose(b(xx), pp(xx), atol=1e-14, rtol=1e-14)\n\n def test_derivative_rndm(self):\n b = _make_random_spline()\n t, c, k = b.tck\n xx = np.linspace(t[0], t[-1], 50)\n xx = np.r_[xx, t]\n\n for der in range(1, k+1):\n yd = splev(xx, (t, c, k), der=der)\n assert_allclose(yd, b(xx, nu=der), atol=1e-14)\n\n # higher derivatives all vanish\n assert_allclose(b(xx, nu=k+1), 0, atol=1e-14)\n\n def test_derivative_jumps(self):\n # example from de Boor, Chap IX, example (24)\n # NB: knots augmented & corresp coefs are zeroed out\n # in agreement with the convention (29)\n k = 2\n t = [-1, -1, 0, 1, 1, 3, 4, 6, 6, 6, 7, 7]\n np.random.seed(1234)\n c = np.r_[0, 0, np.random.random(5), 0, 0]\n b = BSpline(t, c, k)\n\n # b is continuous at x != 6 (triple knot)\n x = np.asarray([1, 3, 4, 6])\n assert_allclose(b(x[x != 6] - 1e-10),\n b(x[x != 6] + 1e-10))\n assert_(not np.allclose(b(6.-1e-10), b(6+1e-10)))\n\n # 1st derivative jumps at double knots, 1 & 6:\n x0 = np.asarray([3, 4])\n assert_allclose(b(x0 - 1e-10, nu=1),\n b(x0 + 1e-10, nu=1))\n x1 = np.asarray([1, 6])\n assert_(not np.all(np.allclose(b(x1 - 1e-10, nu=1),\n b(x1 + 1e-10, nu=1))))\n\n # 2nd derivative is not guaranteed to be continuous either\n assert_(not np.all(np.allclose(b(x - 1e-10, nu=2),\n b(x + 1e-10, nu=2))))\n\n def test_basis_element_quadratic(self):\n xx = np.linspace(-1, 4, 20)\n b = BSpline.basis_element(t=[0, 1, 2, 3])\n assert_allclose(b(xx),\n splev(xx, (b.t, b.c, b.k)), atol=1e-14)\n assert_allclose(b(xx),\n B_0123(xx), atol=1e-14)\n\n b = BSpline.basis_element(t=[0, 1, 1, 2])\n xx = np.linspace(0, 2, 10)\n assert_allclose(b(xx),\n np.where(xx < 1, xx*xx, (2.-xx)**2), atol=1e-14)\n\n def test_basis_element_rndm(self):\n b = _make_random_spline()\n t, c, k = b.tck\n xx = np.linspace(t[k], t[-k-1], 20)\n assert_allclose(b(xx), _sum_basis_elements(xx, t, c, k), atol=1e-14)\n\n def test_cmplx(self):\n b = _make_random_spline()\n t, c, k = b.tck\n cc = c * (1. + 3.j)\n\n b = BSpline(t, cc, k)\n b_re = BSpline(t, b.c.real, k)\n b_im = BSpline(t, b.c.imag, k)\n\n xx = np.linspace(t[k], t[-k-1], 20)\n assert_allclose(b(xx).real, b_re(xx), atol=1e-14)\n assert_allclose(b(xx).imag, b_im(xx), atol=1e-14)\n\n def test_nan(self):\n # nan in, nan out.\n b = BSpline.basis_element([0, 1, 1, 2])\n assert_(np.isnan(b(np.nan)))\n\n def test_derivative_method(self):\n b = _make_random_spline(k=5)\n t, c, k = b.tck\n b0 = BSpline(t, c, k)\n xx = np.linspace(t[k], t[-k-1], 20)\n for j in range(1, k):\n b = b.derivative()\n assert_allclose(b0(xx, j), b(xx), atol=1e-12, rtol=1e-12)\n\n def test_antiderivative_method(self):\n b = _make_random_spline()\n t, c, k = b.tck\n xx = np.linspace(t[k], t[-k-1], 20)\n assert_allclose(b.antiderivative().derivative()(xx),\n b(xx), atol=1e-14, rtol=1e-14)\n\n # repeat with N-D array for c\n c = np.c_[c, c, c]\n c = np.dstack((c, c))\n b = BSpline(t, c, k)\n assert_allclose(b.antiderivative().derivative()(xx),\n b(xx), atol=1e-14, rtol=1e-14)\n\n def test_integral(self):\n b = BSpline.basis_element([0, 1, 2]) # x for x < 1 else 2 - x\n assert_allclose(b.integrate(0, 1), 0.5)\n assert_allclose(b.integrate(1, 0), -1 * 0.5)\n assert_allclose(b.integrate(1, 0), -0.5)\n\n # extrapolate or zeros outside of [0, 2]; default is yes\n assert_allclose(b.integrate(-1, 1), 0)\n assert_allclose(b.integrate(-1, 1, extrapolate=True), 0)\n assert_allclose(b.integrate(-1, 1, extrapolate=False), 0.5)\n assert_allclose(b.integrate(1, -1, extrapolate=False), -1 * 0.5)\n\n # Test ``_fitpack._splint()``\n t, c, k = b.tck\n assert_allclose(b.integrate(1, -1, extrapolate=False),\n _splint(t, c, k, 1, -1)[0])\n\n # Test ``extrapolate='periodic'``.\n b.extrapolate = 'periodic'\n i = b.antiderivative()\n period_int = i(2) - i(0)\n\n assert_allclose(b.integrate(0, 2), period_int)\n assert_allclose(b.integrate(2, 0), -1 * period_int)\n assert_allclose(b.integrate(-9, -7), period_int)\n assert_allclose(b.integrate(-8, -4), 2 * period_int)\n\n assert_allclose(b.integrate(0.5, 1.5), i(1.5) - i(0.5))\n assert_allclose(b.integrate(1.5, 3), i(1) - i(0) + i(2) - i(1.5))\n assert_allclose(b.integrate(1.5 + 12, 3 + 12),\n i(1) - i(0) + i(2) - i(1.5))\n assert_allclose(b.integrate(1.5, 3 + 12),\n i(1) - i(0) + i(2) - i(1.5) + 6 * period_int)\n\n assert_allclose(b.integrate(0, -1), i(0) - i(1))\n assert_allclose(b.integrate(-9, -10), i(0) - i(1))\n assert_allclose(b.integrate(0, -9), i(1) - i(2) - 4 * period_int)\n\n def test_integrate_ppoly(self):\n # test .integrate method to be consistent with PPoly.integrate\n x = [0, 1, 2, 3, 4]\n b = make_interp_spline(x, x)\n b.extrapolate = 'periodic'\n p = PPoly.from_spline(b)\n\n for x0, x1 in [(-5, 0.5), (0.5, 5), (-4, 13)]:\n assert_allclose(b.integrate(x0, x1),\n p.integrate(x0, x1))\n\n def test_subclassing(self):\n # classmethods should not decay to the base class\n class B(BSpline):\n pass\n\n b = B.basis_element([0, 1, 2, 2])\n assert_equal(b.__class__, B)\n assert_equal(b.derivative().__class__, B)\n assert_equal(b.antiderivative().__class__, B)\n\n def test_axis(self):\n n, k = 22, 3\n t = np.linspace(0, 1, n + k + 1)\n sh0 = [6, 7, 8]\n for axis in range(4):\n sh = sh0[:]\n sh.insert(axis, n) # [22, 6, 7, 8] etc\n c = np.random.random(size=sh)\n b = BSpline(t, c, k, axis=axis)\n assert_equal(b.c.shape,\n [sh[axis],] + sh[:axis] + sh[axis+1:])\n\n xp = np.random.random((3, 4, 5))\n assert_equal(b(xp).shape,\n sh[:axis] + list(xp.shape) + sh[axis+1:])\n\n #0 <= axis < c.ndim\n for ax in [-1, c.ndim]:\n assert_raises(ValueError, BSpline, **dict(t=t, c=c, k=k, axis=ax))\n\n # derivative, antiderivative keeps the axis\n for b1 in [BSpline(t, c, k, axis=axis).derivative(),\n BSpline(t, c, k, axis=axis).derivative(2),\n BSpline(t, c, k, axis=axis).antiderivative(),\n BSpline(t, c, k, axis=axis).antiderivative(2)]:\n assert_equal(b1.axis, b.axis)\n\n\ndef test_knots_multiplicity():\n # Take a spline w/ random coefficients, throw in knots of varying\n # multiplicity.\n\n def check_splev(b, j, der=0, atol=1e-14, rtol=1e-14):\n # check evaluations against FITPACK, incl extrapolations\n t, c, k = b.tck\n x = np.unique(t)\n x = np.r_[t[0]-0.1, 0.5*(x[1:] + x[:1]), t[-1]+0.1]\n assert_allclose(splev(x, (t, c, k), der), b(x, der),\n atol=atol, rtol=rtol, err_msg='der = %s k = %s' % (der, b.k))\n\n # test loop itself\n # [the index `j` is for interpreting the traceback in case of a failure]\n for k in [1, 2, 3, 4, 5]:\n b = _make_random_spline(k=k)\n for j, b1 in enumerate(_make_multiples(b)):\n check_splev(b1, j)\n for der in range(1, k+1):\n check_splev(b1, j, der, 1e-12, 1e-12)\n\n\n### stolen from @pv, verbatim\ndef _naive_B(x, k, i, t):\n \"\"\"\n Naive way to compute B-spline basis functions. Useful only for testing!\n computes B(x; t[i],..., t[i+k+1])\n \"\"\"\n if k == 0:\n return 1.0 if t[i] <= x < t[i+1] else 0.0\n if t[i+k] == t[i]:\n c1 = 0.0\n else:\n c1 = (x - t[i])/(t[i+k] - t[i]) * _naive_B(x, k-1, i, t)\n if t[i+k+1] == t[i+1]:\n c2 = 0.0\n else:\n c2 = (t[i+k+1] - x)/(t[i+k+1] - t[i+1]) * _naive_B(x, k-1, i+1, t)\n return (c1 + c2)\n\n\n### stolen from @pv, verbatim\ndef _naive_eval(x, t, c, k):\n \"\"\"\n Naive B-spline evaluation. Useful only for testing!\n \"\"\"\n if x == t[k]:\n i = k\n else:\n i = np.searchsorted(t, x) - 1\n assert t[i] <= x <= t[i+1]\n assert i >= k and i < len(t) - k\n return sum(c[i-j] * _naive_B(x, k, i-j, t) for j in range(0, k+1))\n\n\ndef _naive_eval_2(x, t, c, k):\n \"\"\"Naive B-spline evaluation, another way.\"\"\"\n n = len(t) - (k+1)\n assert n >= k+1\n assert len(c) >= n\n assert t[k] <= x <= t[n]\n return sum(c[i] * _naive_B(x, k, i, t) for i in range(n))\n\n\ndef _sum_basis_elements(x, t, c, k):\n n = len(t) - (k+1)\n assert n >= k+1\n assert len(c) >= n\n s = 0.\n for i in range(n):\n b = BSpline.basis_element(t[i:i+k+2], extrapolate=False)(x)\n s += c[i] * np.nan_to_num(b) # zero out out-of-bounds elements\n return s\n\n\ndef B_012(x):\n \"\"\" A linear B-spline function B(x | 0, 1, 2).\"\"\"\n x = np.atleast_1d(x)\n return np.piecewise(x, [(x < 0) | (x > 2),\n (x >= 0) & (x < 1),\n (x >= 1) & (x <= 2)],\n [lambda x: 0., lambda x: x, lambda x: 2.-x])\n\n\ndef B_0123(x, der=0):\n \"\"\"A quadratic B-spline function B(x | 0, 1, 2, 3).\"\"\"\n x = np.atleast_1d(x)\n conds = [x < 1, (x > 1) & (x < 2), x > 2]\n if der == 0:\n funcs = [lambda x: x*x/2.,\n lambda x: 3./4 - (x-3./2)**2,\n lambda x: (3.-x)**2 / 2]\n elif der == 2:\n funcs = [lambda x: 1.,\n lambda x: -2.,\n lambda x: 1.]\n else:\n raise ValueError('never be here: der=%s' % der)\n pieces = np.piecewise(x, conds, funcs)\n return pieces\n\n\ndef _make_random_spline(n=35, k=3):\n np.random.seed(123)\n t = np.sort(np.random.random(n+k+1))\n c = np.random.random(n)\n return BSpline.construct_fast(t, c, k)\n\n\ndef _make_multiples(b):\n \"\"\"Increase knot multiplicity.\"\"\"\n c, k = b.c, b.k\n\n t1 = b.t.copy()\n t1[17:19] = t1[17]\n t1[22] = t1[21]\n yield BSpline(t1, c, k)\n\n t1 = b.t.copy()\n t1[:k+1] = t1[0]\n yield BSpline(t1, c, k)\n\n t1 = b.t.copy()\n t1[-k-1:] = t1[-1]\n yield BSpline(t1, c, k)\n\n\nclass TestInterop(object):\n #\n # Test that FITPACK-based spl* functions can deal with BSpline objects\n #\n def setup_method(self):\n xx = np.linspace(0, 4.*np.pi, 41)\n yy = np.cos(xx)\n b = make_interp_spline(xx, yy)\n self.tck = (b.t, b.c, b.k)\n self.xx, self.yy, self.b = xx, yy, b\n\n self.xnew = np.linspace(0, 4.*np.pi, 21)\n\n c2 = np.c_[b.c, b.c, b.c]\n self.c2 = np.dstack((c2, c2))\n self.b2 = BSpline(b.t, self.c2, b.k)\n\n def test_splev(self):\n xnew, b, b2 = self.xnew, self.b, self.b2\n\n # check that splev works with 1-D array of coefficients\n # for array and scalar `x`\n assert_allclose(splev(xnew, b),\n b(xnew), atol=1e-15, rtol=1e-15)\n assert_allclose(splev(xnew, b.tck),\n b(xnew), atol=1e-15, rtol=1e-15)\n assert_allclose([splev(x, b) for x in xnew],\n b(xnew), atol=1e-15, rtol=1e-15)\n\n # With N-D coefficients, there's a quirck:\n # splev(x, BSpline) is equivalent to BSpline(x)\n with suppress_warnings() as sup:\n sup.filter(DeprecationWarning,\n \"Calling splev.. with BSpline objects with c.ndim > 1 is not recommended.\")\n assert_allclose(splev(xnew, b2), b2(xnew), atol=1e-15, rtol=1e-15)\n\n # However, splev(x, BSpline.tck) needs some transposes. This is because\n # BSpline interpolates along the first axis, while the legacy FITPACK\n # wrapper does list(map(...)) which effectively interpolates along the\n # last axis. Like so:\n sh = tuple(range(1, b2.c.ndim)) + (0,) # sh = (1, 2, 0)\n cc = b2.c.transpose(sh)\n tck = (b2.t, cc, b2.k)\n assert_allclose(splev(xnew, tck),\n b2(xnew).transpose(sh), atol=1e-15, rtol=1e-15)\n\n def test_splrep(self):\n x, y = self.xx, self.yy\n # test that \"new\" splrep is equivalent to _impl.splrep\n tck = splrep(x, y)\n t, c, k = _impl.splrep(x, y)\n assert_allclose(tck[0], t, atol=1e-15)\n assert_allclose(tck[1], c, atol=1e-15)\n assert_equal(tck[2], k)\n\n # also cover the `full_output=True` branch\n tck_f, _, _, _ = splrep(x, y, full_output=True)\n assert_allclose(tck_f[0], t, atol=1e-15)\n assert_allclose(tck_f[1], c, atol=1e-15)\n assert_equal(tck_f[2], k)\n\n # test that the result of splrep roundtrips with splev:\n # evaluate the spline on the original `x` points\n yy = splev(x, tck)\n assert_allclose(y, yy, atol=1e-15)\n\n # ... and also it roundtrips if wrapped in a BSpline\n b = BSpline(*tck)\n assert_allclose(y, b(x), atol=1e-15)\n\n @pytest.mark.xfail(NumpyVersion(np.__version__) < '1.14.0',\n reason='requires NumPy >= 1.14.0')\n def test_splrep_errors(self):\n # test that both \"old\" and \"new\" splrep raise for an N-D ``y`` array\n # with n > 1\n x, y = self.xx, self.yy\n y2 = np.c_[y, y]\n with assert_raises(ValueError):\n splrep(x, y2)\n with assert_raises(ValueError):\n _impl.splrep(x, y2)\n\n # input below minimum size\n with assert_raises(TypeError, match=\"m > k must hold\"):\n splrep(x[:3], y[:3])\n with assert_raises(TypeError, match=\"m > k must hold\"):\n _impl.splrep(x[:3], y[:3])\n\n def test_splprep(self):\n x = np.arange(15).reshape((3, 5))\n b, u = splprep(x)\n tck, u1 = _impl.splprep(x)\n\n # test the roundtrip with splev for both \"old\" and \"new\" output\n assert_allclose(u, u1, atol=1e-15)\n assert_allclose(splev(u, b), x, atol=1e-15)\n assert_allclose(splev(u, tck), x, atol=1e-15)\n\n # cover the ``full_output=True`` branch\n (b_f, u_f), _, _, _ = splprep(x, s=0, full_output=True)\n assert_allclose(u, u_f, atol=1e-15)\n assert_allclose(splev(u_f, b_f), x, atol=1e-15)\n\n def test_splprep_errors(self):\n # test that both \"old\" and \"new\" code paths raise for x.ndim > 2\n x = np.arange(3*4*5).reshape((3, 4, 5))\n with assert_raises(ValueError, match=\"too many values to unpack\"):\n splprep(x)\n with assert_raises(ValueError, match=\"too many values to unpack\"):\n _impl.splprep(x)\n\n # input below minimum size\n x = np.linspace(0, 40, num=3)\n with assert_raises(TypeError, match=\"m > k must hold\"):\n splprep([x])\n with assert_raises(TypeError, match=\"m > k must hold\"):\n _impl.splprep([x])\n\n # automatically calculated parameters are non-increasing\n # see gh-7589\n x = [-50.49072266, -50.49072266, -54.49072266, -54.49072266]\n with assert_raises(ValueError, match=\"Invalid inputs\"):\n splprep([x])\n with assert_raises(ValueError, match=\"Invalid inputs\"):\n _impl.splprep([x])\n\n # given non-increasing parameter values u\n x = [1, 3, 2, 4]\n u = [0, 0.3, 0.2, 1]\n with assert_raises(ValueError, match=\"Invalid inputs\"):\n splprep(*[[x], None, u])\n\n def test_sproot(self):\n b, b2 = self.b, self.b2\n roots = np.array([0.5, 1.5, 2.5, 3.5])*np.pi\n # sproot accepts a BSpline obj w/ 1-D coef array\n assert_allclose(sproot(b), roots, atol=1e-7, rtol=1e-7)\n assert_allclose(sproot((b.t, b.c, b.k)), roots, atol=1e-7, rtol=1e-7)\n\n # ... and deals with trailing dimensions if coef array is N-D\n with suppress_warnings() as sup:\n sup.filter(DeprecationWarning,\n \"Calling sproot.. with BSpline objects with c.ndim > 1 is not recommended.\")\n r = sproot(b2, mest=50)\n r = np.asarray(r)\n\n assert_equal(r.shape, (3, 2, 4))\n assert_allclose(r - roots, 0, atol=1e-12)\n\n # and legacy behavior is preserved for a tck tuple w/ N-D coef\n c2r = b2.c.transpose(1, 2, 0)\n rr = np.asarray(sproot((b2.t, c2r, b2.k), mest=50))\n assert_equal(rr.shape, (3, 2, 4))\n assert_allclose(rr - roots, 0, atol=1e-12)\n\n def test_splint(self):\n # test that splint accepts BSpline objects\n b, b2 = self.b, self.b2\n assert_allclose(splint(0, 1, b),\n splint(0, 1, b.tck), atol=1e-14)\n assert_allclose(splint(0, 1, b),\n b.integrate(0, 1), atol=1e-14)\n\n # ... and deals with N-D arrays of coefficients\n with suppress_warnings() as sup:\n sup.filter(DeprecationWarning,\n \"Calling splint.. with BSpline objects with c.ndim > 1 is not recommended.\")\n assert_allclose(splint(0, 1, b2), b2.integrate(0, 1), atol=1e-14)\n\n # and the legacy behavior is preserved for a tck tuple w/ N-D coef\n c2r = b2.c.transpose(1, 2, 0)\n integr = np.asarray(splint(0, 1, (b2.t, c2r, b2.k)))\n assert_equal(integr.shape, (3, 2))\n assert_allclose(integr,\n splint(0, 1, b), atol=1e-14)\n\n def test_splder(self):\n for b in [self.b, self.b2]:\n # pad the c array (FITPACK convention)\n ct = len(b.t) - len(b.c)\n if ct > 0:\n b.c = np.r_[b.c, np.zeros((ct,) + b.c.shape[1:])]\n\n for n in [1, 2, 3]:\n bd = splder(b)\n tck_d = _impl.splder((b.t, b.c, b.k))\n assert_allclose(bd.t, tck_d[0], atol=1e-15)\n assert_allclose(bd.c, tck_d[1], atol=1e-15)\n assert_equal(bd.k, tck_d[2])\n assert_(isinstance(bd, BSpline))\n assert_(isinstance(tck_d, tuple)) # back-compat: tck in and out\n\n def test_splantider(self):\n for b in [self.b, self.b2]:\n # pad the c array (FITPACK convention)\n ct = len(b.t) - len(b.c)\n if ct > 0:\n b.c = np.r_[b.c, np.zeros((ct,) + b.c.shape[1:])]\n\n for n in [1, 2, 3]:\n bd = splantider(b)\n tck_d = _impl.splantider((b.t, b.c, b.k))\n assert_allclose(bd.t, tck_d[0], atol=1e-15)\n assert_allclose(bd.c, tck_d[1], atol=1e-15)\n assert_equal(bd.k, tck_d[2])\n assert_(isinstance(bd, BSpline))\n assert_(isinstance(tck_d, tuple)) # back-compat: tck in and out\n\n def test_insert(self):\n b, b2, xx = self.b, self.b2, self.xx\n\n j = b.t.size // 2\n tn = 0.5*(b.t[j] + b.t[j+1])\n\n bn, tck_n = insert(tn, b), insert(tn, (b.t, b.c, b.k))\n assert_allclose(splev(xx, bn),\n splev(xx, tck_n), atol=1e-15)\n assert_(isinstance(bn, BSpline))\n assert_(isinstance(tck_n, tuple)) # back-compat: tck in, tck out\n\n # for N-D array of coefficients, BSpline.c needs to be transposed\n # after that, the results are equivalent.\n sh = tuple(range(b2.c.ndim))\n c_ = b2.c.transpose(sh[1:] + (0,))\n tck_n2 = insert(tn, (b2.t, c_, b2.k))\n\n bn2 = insert(tn, b2)\n\n # need a transpose for comparing the results, cf test_splev\n assert_allclose(np.asarray(splev(xx, tck_n2)).transpose(2, 0, 1),\n bn2(xx), atol=1e-15)\n assert_(isinstance(bn2, BSpline))\n assert_(isinstance(tck_n2, tuple)) # back-compat: tck in, tck out\n\n\nclass TestInterp(object):\n #\n # Test basic ways of constructing interpolating splines.\n #\n xx = np.linspace(0., 2.*np.pi)\n yy = np.sin(xx)\n\n def test_non_int_order(self):\n with assert_raises(TypeError):\n make_interp_spline(self.xx, self.yy, k=2.5)\n\n def test_order_0(self):\n b = make_interp_spline(self.xx, self.yy, k=0)\n assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)\n b = make_interp_spline(self.xx, self.yy, k=0, axis=-1)\n assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)\n\n def test_linear(self):\n b = make_interp_spline(self.xx, self.yy, k=1)\n assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)\n b = make_interp_spline(self.xx, self.yy, k=1, axis=-1)\n assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)\n\n def test_not_a_knot(self):\n for k in [3, 5]:\n b = make_interp_spline(self.xx, self.yy, k)\n assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)\n\n def test_quadratic_deriv(self):\n der = [(1, 8.)] # order, value: f'(x) = 8.\n\n # derivative at right-hand edge\n b = make_interp_spline(self.xx, self.yy, k=2, bc_type=(None, der))\n assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)\n assert_allclose(b(self.xx[-1], 1), der[0][1], atol=1e-14, rtol=1e-14)\n\n # derivative at left-hand edge\n b = make_interp_spline(self.xx, self.yy, k=2, bc_type=(der, None))\n assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)\n assert_allclose(b(self.xx[0], 1), der[0][1], atol=1e-14, rtol=1e-14)\n\n def test_cubic_deriv(self):\n k = 3\n\n # first derivatives at left & right edges:\n der_l, der_r = [(1, 3.)], [(1, 4.)]\n b = make_interp_spline(self.xx, self.yy, k, bc_type=(der_l, der_r))\n assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)\n assert_allclose([b(self.xx[0], 1), b(self.xx[-1], 1)],\n [der_l[0][1], der_r[0][1]], atol=1e-14, rtol=1e-14)\n\n # 'natural' cubic spline, zero out 2nd derivatives at the boundaries\n der_l, der_r = [(2, 0)], [(2, 0)]\n b = make_interp_spline(self.xx, self.yy, k, bc_type=(der_l, der_r))\n assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)\n\n def test_quintic_derivs(self):\n k, n = 5, 7\n x = np.arange(n).astype(np.float_)\n y = np.sin(x)\n der_l = [(1, -12.), (2, 1)]\n der_r = [(1, 8.), (2, 3.)]\n b = make_interp_spline(x, y, k=k, bc_type=(der_l, der_r))\n assert_allclose(b(x), y, atol=1e-14, rtol=1e-14)\n assert_allclose([b(x[0], 1), b(x[0], 2)],\n [val for (nu, val) in der_l])\n assert_allclose([b(x[-1], 1), b(x[-1], 2)],\n [val for (nu, val) in der_r])\n\n @pytest.mark.xfail(reason='unstable')\n def test_cubic_deriv_unstable(self):\n # 1st and 2nd derivative at x[0], no derivative information at x[-1]\n # The problem is not that it fails [who would use this anyway],\n # the problem is that it fails *silently*, and I've no idea\n # how to detect this sort of instability.\n # In this particular case: it's OK for len(t) < 20, goes haywire\n # at larger `len(t)`.\n k = 3\n t = _augknt(self.xx, k)\n\n der_l = [(1, 3.), (2, 4.)]\n b = make_interp_spline(self.xx, self.yy, k, t, bc_type=(der_l, None))\n assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)\n\n def test_knots_not_data_sites(self):\n # Knots need not coincide with the data sites.\n # use a quadratic spline, knots are at data averages,\n # two additional constraints are zero 2nd derivatives at edges\n k = 2\n t = np.r_[(self.xx[0],)*(k+1),\n (self.xx[1:] + self.xx[:-1]) / 2.,\n (self.xx[-1],)*(k+1)]\n b = make_interp_spline(self.xx, self.yy, k, t,\n bc_type=([(2, 0)], [(2, 0)]))\n\n assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)\n assert_allclose([b(self.xx[0], 2), b(self.xx[-1], 2)], [0., 0.],\n atol=1e-14)\n\n def test_minimum_points_and_deriv(self):\n # interpolation of f(x) = x**3 between 0 and 1. f'(x) = 3 * xx**2 and\n # f'(0) = 0, f'(1) = 3.\n k = 3\n x = [0., 1.]\n y = [0., 1.]\n b = make_interp_spline(x, y, k, bc_type=([(1, 0.)], [(1, 3.)]))\n\n xx = np.linspace(0., 1.)\n yy = xx**3\n assert_allclose(b(xx), yy, atol=1e-14, rtol=1e-14)\n\n def test_deriv_spec(self):\n # If one of the derivatives is omitted, the spline definition is\n # incomplete.\n x = y = [1.0, 2, 3, 4, 5, 6]\n\n with assert_raises(ValueError):\n make_interp_spline(x, y, bc_type=([(1, 0.)], None))\n\n with assert_raises(ValueError):\n make_interp_spline(x, y, bc_type=(1, 0.))\n\n with assert_raises(ValueError):\n make_interp_spline(x, y, bc_type=[(1, 0.)])\n\n with assert_raises(ValueError):\n make_interp_spline(x, y, bc_type=42)\n\n # CubicSpline expects`bc_type=(left_pair, right_pair)`, while\n # here we expect `bc_type=(iterable, iterable)`.\n l, r = (1, 0.0), (1, 0.0)\n with assert_raises(ValueError):\n make_interp_spline(x, y, bc_type=(l, r))\n\n def test_complex(self):\n k = 3\n xx = self.xx\n yy = self.yy + 1.j*self.yy\n\n # first derivatives at left & right edges:\n der_l, der_r = [(1, 3.j)], [(1, 4.+2.j)]\n b = make_interp_spline(xx, yy, k, bc_type=(der_l, der_r))\n assert_allclose(b(xx), yy, atol=1e-14, rtol=1e-14)\n assert_allclose([b(xx[0], 1), b(xx[-1], 1)],\n [der_l[0][1], der_r[0][1]], atol=1e-14, rtol=1e-14)\n\n # also test zero and first order\n for k in (0, 1):\n b = make_interp_spline(xx, yy, k=k)\n assert_allclose(b(xx), yy, atol=1e-14, rtol=1e-14)\n\n def test_int_xy(self):\n x = np.arange(10).astype(np.int_)\n y = np.arange(10).astype(np.int_)\n\n # Cython chokes on \"buffer type mismatch\" (construction) or\n # \"no matching signature found\" (evaluation)\n for k in (0, 1, 2, 3):\n b = make_interp_spline(x, y, k=k)\n b(x)\n\n def test_sliced_input(self):\n # Cython code chokes on non C contiguous arrays\n xx = np.linspace(-1, 1, 100)\n\n x = xx[::5]\n y = xx[::5]\n\n for k in (0, 1, 2, 3):\n make_interp_spline(x, y, k=k)\n\n def test_check_finite(self):\n # check_finite defaults to True; nans and such trigger a ValueError\n x = np.arange(10).astype(float)\n y = x**2\n\n for z in [np.nan, np.inf, -np.inf]:\n y[-1] = z\n assert_raises(ValueError, make_interp_spline, x, y)\n\n @pytest.mark.parametrize('k', [1, 2, 3, 5])\n def test_list_input(self, k):\n # regression test for gh-8714: TypeError for x, y being lists and k=2\n x = list(range(10))\n y = [a**2 for a in x]\n make_interp_spline(x, y, k=k)\n\n def test_multiple_rhs(self):\n yy = np.c_[np.sin(self.xx), np.cos(self.xx)]\n der_l = [(1, [1., 2.])]\n der_r = [(1, [3., 4.])]\n\n b = make_interp_spline(self.xx, yy, k=3, bc_type=(der_l, der_r))\n assert_allclose(b(self.xx), yy, atol=1e-14, rtol=1e-14)\n assert_allclose(b(self.xx[0], 1), der_l[0][1], atol=1e-14, rtol=1e-14)\n assert_allclose(b(self.xx[-1], 1), der_r[0][1], atol=1e-14, rtol=1e-14)\n\n def test_shapes(self):\n np.random.seed(1234)\n k, n = 3, 22\n x = np.sort(np.random.random(size=n))\n y = np.random.random(size=(n, 5, 6, 7))\n\n b = make_interp_spline(x, y, k)\n assert_equal(b.c.shape, (n, 5, 6, 7))\n\n # now throw in some derivatives\n d_l = [(1, np.random.random((5, 6, 7)))]\n d_r = [(1, np.random.random((5, 6, 7)))]\n b = make_interp_spline(x, y, k, bc_type=(d_l, d_r))\n assert_equal(b.c.shape, (n + k - 1, 5, 6, 7))\n\n def test_string_aliases(self):\n yy = np.sin(self.xx)\n\n # a single string is duplicated\n b1 = make_interp_spline(self.xx, yy, k=3, bc_type='natural')\n b2 = make_interp_spline(self.xx, yy, k=3, bc_type=([(2, 0)], [(2, 0)]))\n assert_allclose(b1.c, b2.c, atol=1e-15)\n\n # two strings are handled\n b1 = make_interp_spline(self.xx, yy, k=3,\n bc_type=('natural', 'clamped'))\n b2 = make_interp_spline(self.xx, yy, k=3,\n bc_type=([(2, 0)], [(1, 0)]))\n assert_allclose(b1.c, b2.c, atol=1e-15)\n\n # one-sided BCs are OK\n b1 = make_interp_spline(self.xx, yy, k=2, bc_type=(None, 'clamped'))\n b2 = make_interp_spline(self.xx, yy, k=2, bc_type=(None, [(1, 0.0)]))\n assert_allclose(b1.c, b2.c, atol=1e-15)\n\n # 'not-a-knot' is equivalent to None\n b1 = make_interp_spline(self.xx, yy, k=3, bc_type='not-a-knot')\n b2 = make_interp_spline(self.xx, yy, k=3, bc_type=None)\n assert_allclose(b1.c, b2.c, atol=1e-15)\n\n # unknown strings do not pass\n with assert_raises(ValueError):\n make_interp_spline(self.xx, yy, k=3, bc_type='typo')\n\n # string aliases are handled for 2D values\n yy = np.c_[np.sin(self.xx), np.cos(self.xx)]\n der_l = [(1, [0., 0.])]\n der_r = [(2, [0., 0.])]\n b2 = make_interp_spline(self.xx, yy, k=3, bc_type=(der_l, der_r))\n b1 = make_interp_spline(self.xx, yy, k=3,\n bc_type=('clamped', 'natural'))\n assert_allclose(b1.c, b2.c, atol=1e-15)\n\n # ... and for N-D values:\n np.random.seed(1234)\n k, n = 3, 22\n x = np.sort(np.random.random(size=n))\n y = np.random.random(size=(n, 5, 6, 7))\n\n # now throw in some derivatives\n d_l = [(1, np.zeros((5, 6, 7)))]\n d_r = [(1, np.zeros((5, 6, 7)))]\n b1 = make_interp_spline(x, y, k, bc_type=(d_l, d_r))\n b2 = make_interp_spline(x, y, k, bc_type='clamped')\n assert_allclose(b1.c, b2.c, atol=1e-15)\n\n def test_full_matrix(self):\n np.random.seed(1234)\n k, n = 3, 7\n x = np.sort(np.random.random(size=n))\n y = np.random.random(size=n)\n t = _not_a_knot(x, k)\n\n b = make_interp_spline(x, y, k, t)\n cf = make_interp_full_matr(x, y, t, k)\n assert_allclose(b.c, cf, atol=1e-14, rtol=1e-14)\n\n\ndef make_interp_full_matr(x, y, t, k):\n \"\"\"Assemble an spline order k with knots t to interpolate\n y(x) using full matrices.\n Not-a-knot BC only.\n\n This routine is here for testing only (even though it's functional).\n \"\"\"\n assert x.size == y.size\n assert t.size == x.size + k + 1\n n = x.size\n\n A = np.zeros((n, n), dtype=np.float_)\n\n for j in range(n):\n xval = x[j]\n if xval == t[k]:\n left = k\n else:\n left = np.searchsorted(t, xval) - 1\n\n # fill a row\n bb = _bspl.evaluate_all_bspl(t, k, xval, left)\n A[j, left-k:left+1] = bb\n\n c = sl.solve(A, y)\n return c\n\n\n### XXX: 'periodic' interp spline using full matrices\ndef make_interp_per_full_matr(x, y, t, k):\n x, y, t = map(np.asarray, (x, y, t))\n\n n = x.size\n nt = t.size - k - 1\n\n # have `n` conditions for `nt` coefficients; need nt-n derivatives\n assert nt - n == k - 1\n\n # LHS: the collocation matrix + derivatives at edges\n A = np.zeros((nt, nt), dtype=np.float_)\n\n # derivatives at x[0]:\n offset = 0\n\n if x[0] == t[k]:\n left = k\n else:\n left = np.searchsorted(t, x[0]) - 1\n\n if x[-1] == t[k]:\n left2 = k\n else:\n left2 = np.searchsorted(t, x[-1]) - 1\n\n for i in range(k-1):\n bb = _bspl.evaluate_all_bspl(t, k, x[0], left, nu=i+1)\n A[i, left-k:left+1] = bb\n bb = _bspl.evaluate_all_bspl(t, k, x[-1], left2, nu=i+1)\n A[i, left2-k:left2+1] = -bb\n offset += 1\n\n # RHS\n y = np.r_[[0]*(k-1), y]\n\n # collocation matrix\n for j in range(n):\n xval = x[j]\n # find interval\n if xval == t[k]:\n left = k\n else:\n left = np.searchsorted(t, xval) - 1\n\n # fill a row\n bb = _bspl.evaluate_all_bspl(t, k, xval, left)\n A[j + offset, left-k:left+1] = bb\n\n c = sl.solve(A, y)\n return c\n\n\ndef make_lsq_full_matrix(x, y, t, k=3):\n \"\"\"Make the least-square spline, full matrices.\"\"\"\n x, y, t = map(np.asarray, (x, y, t))\n m = x.size\n n = t.size - k - 1\n\n A = np.zeros((m, n), dtype=np.float_)\n\n for j in range(m):\n xval = x[j]\n # find interval\n if xval == t[k]:\n left = k\n else:\n left = np.searchsorted(t, xval) - 1\n\n # fill a row\n bb = _bspl.evaluate_all_bspl(t, k, xval, left)\n A[j, left-k:left+1] = bb\n\n # have observation matrix, can solve the LSQ problem\n B = np.dot(A.T, A)\n Y = np.dot(A.T, y)\n c = sl.solve(B, Y)\n\n return c, (A, Y)\n\n\nclass TestLSQ(object):\n #\n # Test make_lsq_spline\n #\n np.random.seed(1234)\n n, k = 13, 3\n x = np.sort(np.random.random(n))\n y = np.random.random(n)\n t = _augknt(np.linspace(x[0], x[-1], 7), k)\n\n def test_lstsq(self):\n # check LSQ construction vs a full matrix version\n x, y, t, k = self.x, self.y, self.t, self.k\n\n c0, AY = make_lsq_full_matrix(x, y, t, k)\n b = make_lsq_spline(x, y, t, k)\n\n assert_allclose(b.c, c0)\n assert_equal(b.c.shape, (t.size - k - 1,))\n\n # also check against numpy.lstsq\n aa, yy = AY\n c1, _, _, _ = np.linalg.lstsq(aa, y, rcond=-1)\n assert_allclose(b.c, c1)\n\n def test_weights(self):\n # weights = 1 is same as None\n x, y, t, k = self.x, self.y, self.t, self.k\n w = np.ones_like(x)\n\n b = make_lsq_spline(x, y, t, k)\n b_w = make_lsq_spline(x, y, t, k, w=w)\n\n assert_allclose(b.t, b_w.t, atol=1e-14)\n assert_allclose(b.c, b_w.c, atol=1e-14)\n assert_equal(b.k, b_w.k)\n\n def test_multiple_rhs(self):\n x, t, k, n = self.x, self.t, self.k, self.n\n y = np.random.random(size=(n, 5, 6, 7))\n\n b = make_lsq_spline(x, y, t, k)\n assert_equal(b.c.shape, (t.size-k-1, 5, 6, 7))\n\n def test_complex(self):\n # cmplx-valued `y`\n x, t, k = self.x, self.t, self.k\n yc = self.y * (1. + 2.j)\n\n b = make_lsq_spline(x, yc, t, k)\n b_re = make_lsq_spline(x, yc.real, t, k)\n b_im = make_lsq_spline(x, yc.imag, t, k)\n\n assert_allclose(b(x), b_re(x) + 1.j*b_im(x), atol=1e-15, rtol=1e-15)\n\n def test_int_xy(self):\n x = np.arange(10).astype(np.int_)\n y = np.arange(10).astype(np.int_)\n t = _augknt(x, k=1)\n # Cython chokes on \"buffer type mismatch\"\n make_lsq_spline(x, y, t, k=1)\n\n def test_sliced_input(self):\n # Cython code chokes on non C contiguous arrays\n xx = np.linspace(-1, 1, 100)\n\n x = xx[::3]\n y = xx[::3]\n t = _augknt(x, 1)\n make_lsq_spline(x, y, t, k=1)\n\n def test_checkfinite(self):\n # check_finite defaults to True; nans and such trigger a ValueError\n x = np.arange(12).astype(float)\n y = x**2\n t = _augknt(x, 3)\n\n for z in [np.nan, np.inf, -np.inf]:\n y[-1] = z\n assert_raises(ValueError, make_lsq_spline, x, y, t)\n" ]
[ [ "scipy.interpolate._fitpack_impl.splrep", "numpy.testing.assert_allclose", "numpy.dot", "numpy.ones_like", "scipy.interpolate.BSpline", "scipy.interpolate._fitpack._splint", "numpy.testing.suppress_warnings", "numpy.where", "scipy.interpolate.PPoly.from_spline", "numpy.linalg.lstsq", "numpy.cos", "scipy.interpolate.make_lsq_spline", "numpy.random.random", "scipy.interpolate._fitpack_impl.splantider", "scipy.linalg.solve", "scipy.interpolate.sproot", "numpy.sin", "scipy.interpolate.make_interp_spline", "numpy.nan_to_num", "scipy.interpolate.BSpline.construct_fast", "scipy.interpolate._fitpack_impl.splprep", "scipy._lib._version.NumpyVersion", "numpy.arange", "scipy.interpolate.splantider", "numpy.array", "scipy.interpolate.BSpline.basis_element", "numpy.zeros", "numpy.testing.assert_equal", "numpy.piecewise", "scipy.interpolate.insert", "scipy.interpolate.splder", "scipy.interpolate.splprep", "numpy.dstack", "scipy.interpolate._bsplines._not_a_knot", "numpy.searchsorted", "numpy.isnan", "numpy.asarray", "numpy.errstate", "numpy.random.seed", "scipy.interpolate.splrep", "scipy.interpolate._bsplines._augknt", "numpy.atleast_1d", "scipy.interpolate._bspl.evaluate_all_bspl", "scipy.interpolate.splev", "numpy.linspace", "scipy.interpolate._fitpack_impl.splder", "numpy.unique", "scipy.interpolate.splint" ] ]
dizcza/EmbedderSDR
[ "52e48efcddab44ed5040ea98e7e886a600cc0632" ]
[ "experiment/kwta_inverse.py" ]
[ "from collections import defaultdict\n\nimport torch\nimport torch.utils.data\nimport torchvision\nimport torchvision.transforms.functional as F\nfrom PIL import Image\nfrom torchvision.datasets import MNIST\n\nfrom mighty.monitor.viz import VisdomMighty\nfrom mighty.utils.data import DataLoader\nfrom mighty.utils.data.transforms_default import TransformDefault\nfrom mighty.utils.var_online import MeanOnline\nfrom models.kwta import KWinnersTakeAllFunction\nfrom utils.signal import factors_root\n\n\ndef torch_to_matplotlib(image):\n if image.shape[0] == 1:\n return image.squeeze(dim=0)\n else:\n return image.transpose(0, 1).transpose(1, 2)\n\n\ndef undo_normalization(images_normalized, normalize_inverse):\n tensor = torch.stack(list(map(normalize_inverse, images_normalized)))\n tensor.clamp_(0, 1)\n return tensor\n\n\ndef kwta_inverse(embedding_dim=10000, sparsity=0.05, dataset_cls=MNIST):\n loader = DataLoader(dataset_cls, transform=TransformDefault.mnist(), batch_size=32)\n images, labels = loader.sample()\n batch_size, channels, height, width = images.shape\n images_binary = (images > 0).type(torch.float32)\n sparsity_input = images_binary.mean()\n print(f\"Sparsity input raw image: {sparsity_input:.3f}\")\n images_flatten = images.flatten(start_dim=2)\n weights = torch.randn(images_flatten.shape[2], embedding_dim)\n embeddings = images_flatten @ weights\n kwta_embeddings = KWinnersTakeAllFunction.apply(embeddings.clone(), sparsity)\n before_inverse = kwta_embeddings @ weights.transpose(0, 1)\n restored = KWinnersTakeAllFunction.apply(before_inverse.clone(), sparsity_input)\n\n kwta_embeddings = kwta_embeddings.view(batch_size, channels, *factors_root(embedding_dim))\n restored = restored.view_as(images)\n\n images = undo_normalization(images, loader.normalize_inverse)\n\n viz = VisdomMighty(env=\"kWTA inverse\")\n resize = torchvision.transforms.Resize(size=128, interpolation=Image.NEAREST)\n transformed_images = []\n for orig, kwta, restored in zip(images, kwta_embeddings, restored):\n transformed_images.append(resize(orig))\n transformed_images.append(resize(kwta))\n transformed_images.append(resize(restored))\n transformed_images = torch.stack(transformed_images, dim=0) # (3*B, 1, 128, 128)\n print(transformed_images.shape)\n viz.images(transformed_images, win='images', nrow=3, opts=dict(\n title=f\"Original | kWTA(n={embedding_dim}, sparsity={sparsity}) | Restored\",\n ))\n\n\ndef calc_overlap(vec1, vec2):\n \"\"\"\n :param vec1: batch of binary vectors\n :param vec2: batch of binary vectors\n :return: (float) vec1 and vec2 similarity (overlap)\n \"\"\"\n vec1 = vec1.flatten(start_dim=1)\n vec2 = vec2.flatten(start_dim=1)\n k_active = (vec1.sum(dim=1) + vec2.sum(dim=1)) / 2\n similarity = (vec1 * vec2).sum(dim=1) / k_active\n similarity = similarity.mean()\n return similarity\n\n\ndef kwta_translation_similarity(embedding_dim=10000, sparsity=0.05,\n translate=(1, 1), dataset_cls=MNIST):\n loader = DataLoader(dataset_cls, transform=TransformDefault.mnist())\n images, labels = loader.sample()\n images = (images > 0).type(torch.float32)\n\n images_translated = []\n for im in images:\n im_pil = F.to_pil_image(im)\n im_translated = F.affine(im_pil, angle=0, translate=translate, scale=1, shear=0)\n im_translated = F.to_tensor(im_translated)\n images_translated.append(im_translated)\n images_translated = torch.stack(images_translated, dim=0)\n assert images_translated.unique(sorted=True).tolist() == [0, 1]\n\n w, h = images.shape[2:]\n weights = torch.randn(w * h, embedding_dim)\n\n def apply_kwta(images_input):\n \"\"\"\n :param images_input: (B, C, W, H) images tensor\n :return: (B, C, k_active) kwta encoded SDR tensor\n \"\"\"\n images_flatten = images_input.flatten(start_dim=2)\n embeddings = images_flatten @ weights\n kwta_embedding = KWinnersTakeAllFunction.apply(embeddings.clone(), sparsity)\n return kwta_embedding\n\n kwta_orig = apply_kwta(images)\n kwta_translated = apply_kwta(images_translated)\n\n print(f\"input image ORIG vs TRANSLATED similarity {calc_overlap(images, images_translated):.3f}\")\n print(f\"random-kWTA ORIG vs TRANSLATED similarity: {calc_overlap(kwta_orig, kwta_translated):.3f}\")\n\n\ndef surfplot(dataset_cls=MNIST):\n loader = DataLoader(dataset_cls, transform=TransformDefault.mnist(), eval_size=1000)\n logdim = torch.arange(8, 14)\n embedding_dimensions = torch.pow(2, logdim)\n sparsities = [0.001, 0.01, 0.05, 0.1, 0.3, 0.5, 0.75]\n overlap_running_mean = defaultdict(lambda: defaultdict(MeanOnline))\n for images, labels in loader.eval(description=f\"kWTA inverse overlap surfplot \"\n f\"({dataset_cls.__name__})\"):\n if torch.cuda.is_available():\n images = images.cuda()\n images_binary = (images > 0).type(torch.float32).flatten(start_dim=2)\n sparsity_channel = images_binary.mean()\n for i, embedding_dim in enumerate(embedding_dimensions):\n for j, sparsity in enumerate(sparsities):\n weights = torch.randn(images_binary.shape[2], embedding_dim, device=images_binary.device)\n embeddings = images_binary @ weights\n kwta_embeddings = KWinnersTakeAllFunction.apply(embeddings, sparsity)\n before_inverse = kwta_embeddings @ weights.transpose(0, 1)\n restored = KWinnersTakeAllFunction.apply(before_inverse, sparsity_channel)\n overlap = calc_overlap(images_binary, restored)\n overlap_running_mean[i][j].update(overlap)\n overlap = torch.empty(len(embedding_dimensions), len(sparsities))\n for i in range(overlap.shape[0]):\n for j in range(overlap.shape[1]):\n overlap[i, j] = overlap_running_mean[i][j].get_mean()\n\n viz = VisdomMighty(env=\"kWTA inverse\")\n opts = dict(\n title=f\"kWTA inverse overlap: {dataset_cls.__name__}\",\n ytickvals=list(range(len(embedding_dimensions))),\n yticklabels=[f'2^{power}' for power in logdim],\n ylabel='embedding_dim',\n xtickvals=list(range(len(sparsities))),\n xticklabels=list(map(str, sparsities)),\n xlabel='sparsity',\n )\n viz.contour(X=overlap, win=f'overlap contour: {dataset_cls.__name__}', opts=opts)\n viz.surf(X=overlap, win=f'overlap surf: {dataset_cls.__name__}', opts=opts)\n\n\nif __name__ == '__main__':\n kwta_inverse()\n surfplot()\n kwta_translation_similarity()\n" ]
[ [ "torch.stack", "torch.arange", "torch.cuda.is_available", "torch.randn", "torch.pow" ] ]
BrouBoni/segmentation_RT
[ "e44f4fafe23652f3122a5e65bd8515283dcfdbe0" ]
[ "segmentation_rt/dl/model/model.py" ]
[ "import os\nimport random\nimport time\nfrom collections import OrderedDict\nfrom datetime import datetime\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport torchio as tio\nfrom torch.utils.tensorboard import SummaryWriter\n\nimport segmentation_rt.dl.model.networks as networks\nfrom segmentation_rt.util.util import print_log, format_log\n\n\nclass Model(object):\n \"\"\"\n Initialize a chosen model with parameters.\n\n This class allows the training of the networks and afterward for testing.Only resnet available, more coming soon.\n\n :param expr_dir: output folder.\n :type expr_dir: str\n :param seed: manual seed.\n :type seed: int\n :param batch_size: input batch size.\n :type batch_size: int\n :param epoch_count: the starting epoch count.\n :type epoch_count: int\n :param niter: # of iter at starting learning rate.\n :type niter: int\n :param niter_decay: # of iter to linearly decay learning rate to zero.\n :type niter_decay: int\n :param beta1: momentum term of adam.\n :type beta1: float\n :param lr: initial learning rate for adam.\n :type lr: float\n :param ngf: # of gen filters in first conv layer.\n :type ngf: int\n :param n_blocks: # of residual blocks in the global generator network.\n :type n_blocks: int\n :param input_nc: the number of channels in input images.\n :type input_nc: int\n :param ngf: the number of filters in the last conv layer.\n :type ngf: int\n :param n_blocks: the number of ResNet blocks.\n :type n_blocks: int\n :param use_dropout: if use dropout layers.\n :type use_dropout: bool\n :param norm: normalization.\n :type norm: str\n :param max_grad_norm: max grad norm to which it will be clipped (if exceeded).\n :type max_grad_norm: float\n :param monitor_grad_norm: flag set to monitor grad norms.\n :type monitor_grad_norm: bool\n :param save_epoch_freq: frequency of saving checkpoints at the end of epochs.\n :type save_epoch_freq: int\n :param print_freq: frequency of showing training results on console.\n :type print_freq: int\n :param testing: if test phase.\n :type testing: bool\n \"\"\"\n\n def __init__(self, expr_dir, structures, seed=None, batch_size=None,\n epoch_count=1, niter=150, niter_decay=50, beta1=0.5, lr=0.0002,\n ngf=64, n_blocks=9, input_nc=1, use_dropout=False, norm='batch', max_grad_norm=500.,\n monitor_grad_norm=True, save_epoch_freq=2, print_freq=60, display_epoch_freq=1, testing=False,\n resume=False):\n\n self.expr_dir = expr_dir\n self.structures = structures\n self.seed = seed\n self.device = torch.device('cuda') if torch.cuda.is_available() else 'cpu'\n self.batch_size = batch_size\n\n self.epoch_count = epoch_count\n self.niter = niter\n self.niter_decay = niter_decay\n self.beta1 = beta1\n self.lr = lr\n self.old_lr = self.lr\n\n self.ngf = ngf\n self.n_blocks = n_blocks\n self.input_nc = input_nc\n self.output_nc = len(structures) + 1\n self.use_dropout = use_dropout\n self.norm = norm\n self.max_grad_norm = max_grad_norm\n\n self.monitor_grad_norm = monitor_grad_norm\n self.save_epoch_freq = save_epoch_freq\n self.print_freq = print_freq\n self.display_epoch_freq = display_epoch_freq\n self.time = datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n\n # define network we need here\n self.netG = networks.define_generator(input_nc=self.input_nc, output_nc=self.output_nc, ngf=self.ngf,\n n_blocks=self.n_blocks, use_dropout=self.use_dropout,\n device=self.device)\n\n # define all optimizers here\n self.optimizer_G = torch.optim.Adam(self.netG.parameters(),\n lr=self.lr, betas=(self.beta1, 0.999))\n weights = [1 for _ in range(self.output_nc)]\n class_weights = torch.FloatTensor(weights).to(self.device)\n self.loss = torch.nn.CrossEntropyLoss(weight=class_weights)\n\n if not os.path.exists(expr_dir):\n os.makedirs(expr_dir)\n\n if not os.path.exists(os.path.join(expr_dir, 'TensorBoard')):\n os.makedirs(os.path.join(expr_dir, 'TensorBoard', self.time))\n\n if not os.path.exists(os.path.join(expr_dir, 'training_visuals')):\n os.makedirs(os.path.join(expr_dir, 'training_visuals'))\n\n if not testing:\n num_params = 0\n with open(\"%s/nets.txt\" % self.expr_dir, 'w') as nets_f:\n num_params += networks.print_network(self.netG, nets_f)\n nets_f.write('# parameters: %d\\n' % num_params)\n nets_f.flush()\n\n if resume:\n self.load(os.path.join(self.expr_dir, \"latest\"), True)\n\n def train(self, train_dataset, test_dataset=None):\n \"\"\"\n Train the model with a dataset.\n\n :param train_dataset: training dataset.\n :type train_dataset: :class:`DataLoader`\n :param test_dataset: test dataset. If given output statistic during training.\n :type test_dataset: :class:`DataLoader`\n \"\"\"\n self.batch_size = train_dataset.batch_size\n self.save_options()\n out_f = open(f\"{self.expr_dir}/results.txt\", 'w')\n use_gpu = torch.cuda.is_available()\n\n tensorbard_writer = SummaryWriter(os.path.join(self.expr_dir, 'TensorBoard', self.time))\n\n if self.seed is not None:\n print(f\"using random seed: {self.seed}\")\n random.seed(self.seed)\n np.random.seed(self.seed)\n torch.manual_seed(self.seed)\n if use_gpu:\n torch.cuda.manual_seed_all(self.seed)\n\n total_steps = 0\n print_start_time = time.time()\n\n for epoch in range(self.epoch_count, self.niter + self.niter_decay + 1):\n epoch_start_time = time.time()\n epoch_iter = 0\n\n for data in train_dataset:\n ct = data['ct'][tio.DATA].to(self.device)\n mask = data['label_map'][tio.DATA].to(self.device)\n ct = ct.transpose_(2, 4)\n mask = torch.squeeze(mask.transpose_(2, 4), 1)\n total_steps += self.batch_size\n epoch_iter += self.batch_size\n\n if self.monitor_grad_norm:\n losses, visuals, _ = self.train_instance(ct, mask)\n else:\n losses, visuals = self.train_instance(ct, mask)\n\n if total_steps % self.print_freq == 0:\n t = (time.time() - print_start_time) / self.batch_size\n print_log(out_f, format_log(epoch, epoch_iter, losses, t))\n tensorbard_writer.add_scalars('losses', {'Cross entropy loss': losses['Loss']}, total_steps)\n print_start_time = time.time()\n\n if epoch % self.display_epoch_freq == 0:\n self.visualize_training(visuals, data['ct'][tio.AFFINE], epoch, epoch_iter / self.batch_size)\n\n if epoch % self.save_epoch_freq == 0:\n print_log(out_f, 'saving the model at the end of epoch %d, iterations %d' %\n (epoch, total_steps))\n self.save('latest')\n\n print_log(out_f, 'End of epoch %d / %d \\t Time Taken: %d sec' %\n (epoch, self.niter + self.niter_decay, time.time() - epoch_start_time))\n\n if epoch > self.niter:\n self.update_learning_rate()\n\n out_f.close()\n tensorbard_writer.close()\n\n def train_instance(self, ct, segmentation):\n \"\"\"\n Training instance (batch).\n\n :param ct: input tensor.\n :type ct: Tensor\n :param segmentation: ground truth tensor.\n :type segmentation: Tensor\n :return: losses and visualization data.\n \"\"\"\n fake_segmentation = self.netG.forward(ct)\n self.optimizer_G.zero_grad()\n loss = self.loss(fake_segmentation, segmentation)\n loss.backward()\n grad_norm = torch.nn.utils.clip_grad_norm_(self.netG.parameters(), self.max_grad_norm)\n self.optimizer_G.step()\n\n losses = OrderedDict([('Loss', loss.data.item())])\n visuals = OrderedDict([('ct', ct.data),\n ('segmentation_mask', segmentation.data),\n ('fake_segmentation_mask', fake_segmentation.data)\n ])\n if self.monitor_grad_norm:\n grad_norm = OrderedDict([('grad_norm', grad_norm)])\n\n return losses, visuals, grad_norm\n\n return losses, visuals\n\n def update_learning_rate(self):\n \"\"\"Update learning rate.\"\"\"\n lrd = self.lr / self.niter_decay\n lr = self.old_lr - lrd\n for param_group in self.optimizer_G.param_groups:\n param_group['lr'] = lr\n\n print('update learning rate: %f -> %f' % (self.old_lr, lr))\n self.old_lr = lr\n\n def save(self, checkpoint_name):\n \"\"\"\n Save the model and optimizer.\n\n :param checkpoint_name: name of the checkpoint.\n :type checkpoint_name: str\n \"\"\"\n checkpoint_path = os.path.join(self.expr_dir, checkpoint_name)\n checkpoint = {\n 'netG': self.netG.state_dict(),\n 'optimizer_G': self.optimizer_G.state_dict()\n }\n torch.save(checkpoint, checkpoint_path)\n\n def load(self, checkpoint_path, optimizer=False):\n \"\"\"\n Loads an object saved with torch.save from a file.\n\n :param checkpoint_path: path to the checkpoint.\n :type checkpoint_path: str\n :param optimizer: with optimizer.\n :type optimizer: bool\n \"\"\"\n checkpoint = torch.load(checkpoint_path)\n self.netG.load_state_dict(checkpoint['netG'])\n\n if optimizer:\n self.optimizer_G.load_state_dict(checkpoint['optimizer_G'])\n\n def eval(self):\n \"\"\"Sets the module in evaluation mode.\"\"\"\n self.netG.eval()\n\n def visualize_training(self, visuals, affine, epoch, index):\n \"\"\"\n Save training image for visualization.\n\n :param affine:\n :param visuals: images.\n :type visuals: dict\n :param epoch: epoch\n :type epoch: int\n :param index: index\n :type index: float\n \"\"\"\n ct = visuals['ct'].cpu().transpose_(2, 4)\n visuals['segmentation_mask'] = torch.unsqueeze(visuals['segmentation_mask'].cpu(), 1).transpose_(2, 4)\n visuals['fake_segmentation_mask'] = visuals['fake_segmentation_mask'].cpu().transpose_(2, 4)\n\n segmentation_mask = visuals['segmentation_mask']\n fake_segmentation_mask = visuals['fake_segmentation_mask'].argmax(dim=1, keepdim=True)\n\n for i in range(ct.shape[0]):\n subject = tio.Subject(\n ct=tio.ScalarImage(tensor=ct[i], affine=affine[i]),\n segmentation_mask=tio.LabelMap(tensor=segmentation_mask[i], affine=affine[i]),\n fake_segmentation_mask=tio.LabelMap(tensor=fake_segmentation_mask[i], affine=affine[i])\n )\n\n save_path = os.path.join(self.expr_dir, \"training_visuals\")\n save_path = os.path.join(save_path, 'cycle_%02d_%04d_%02d.png' % (epoch, index, i))\n subject.plot(show=False, output_path=save_path)\n plt.close('all')\n\n def save_options(self):\n \"\"\"Save model options.\"\"\"\n # ToDo deal with none default type (not working with parse_opt_file()\n options_file = open(f\"{self.expr_dir}/options.txt\", 'wt')\n print_log(options_file, '------------ Options -------------')\n for k, v in sorted(self.__dict__.items()):\n print_log(options_file, '%s: %s' % (str(k), str(v)))\n print_log(options_file, '-------------- End ----------------')\n\n def test(self, dataset, export_path=None, checkpoint=None, save=False):\n \"\"\"\n Model prediction for a SingleDataset.\n\n :param dataset: training dataset.\n :type dataset: :class:`DataLoader`\n :param export_path: export path.\n :type export_path: str\n :return: MAE of the dataset.\n :rtype: float\n \"\"\"\n checkpoint = checkpoint or os.path.join(self.expr_dir, \"latest\")\n self.load(checkpoint)\n self.eval()\n\n prediction_path = export_path or self.expr_dir\n if not os.path.exists(prediction_path):\n os.makedirs(prediction_path)\n\n start = time.time()\n with torch.no_grad():\n for i, data in enumerate(dataset.loader):\n ct = data['ct'][tio.DATA].to(self.device)\n ct = ct.transpose_(2, 4)\n locations = data[tio.LOCATION]\n\n fake_segmentation = self.netG.forward(ct)\n fake_segmentation = fake_segmentation.transpose_(2, 4)\n\n dataset.aggregator.add_batch(fake_segmentation, locations)\n\n print(f\"patch {i + 1}/{len(dataset.loader)}\")\n affine = dataset.transform(dataset.subject['ct']).affine\n foreground = dataset.aggregator.get_output_tensor()\n fake_segmentation_mask = foreground.argmax(dim=0, keepdim=True).type(torch.int8)\n prediction = tio.LabelMap(tensor=fake_segmentation_mask, affine=affine)\n print(f\"{time.time() - start} sec. for evaluation\")\n if save:\n prediction.save(os.path.join(prediction_path, 'fake_segmentation.nii'))\n return prediction\n" ]
[ [ "torch.device", "torch.cuda.manual_seed_all", "numpy.random.seed", "torch.save", "torch.no_grad", "torch.FloatTensor", "matplotlib.pyplot.close", "torch.manual_seed", "torch.cuda.is_available", "torch.load", "torch.nn.CrossEntropyLoss" ] ]
DwaraknathT/pyfl
[ "e9a4d1ca98c6167a567d0d46771ac9e1c7bb7322" ]
[ "pyfl/models/resnet.py" ]
[ "'''\nProperly implemented ResNet-s for CIFAR10 as described in paper [1].\nThe implementation and structure of this file is hugely influenced by [2]\nwhich is implemented for ImageNet and doesn't have option A for identity.\nMoreover, most of the implementations on the web is copy-paste from\ntorchvision's resnet and has wrong number of params.\nProper ResNet-s for CIFAR10 (for fair comparision and etc.) has following\nnumber of layers and parameters:\nname | layers | params\nResNet20 | 20 | 0.27M\nResNet32 | 32 | 0.46M\nResNet44 | 44 | 0.66M\nResNet56 | 56 | 0.85M\nResNet110 | 110 | 1.7M\nResNet1202| 1202 | 19.4m\nwhich this implementation indeed has.\nReference:\n[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun\n Deep Residual Learning for Image Recognition. arXiv:1512.03385\n[2] https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py\nIf you use this implementation in you work, please don't forget to mention the\nauthor, Yerlan Idelbayev.\n'''\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.init as init\n\nfrom pyfl.models.layers import MaskedConv\n\n__all__ = ['ResNet', 'resnet20', 'resnet32', 'resnet44', 'resnet56', 'resnet110', 'resnet1202']\n\n\ndef _weights_init(m):\n classname = m.__class__.__name__\n # print(classname)\n if isinstance(m, nn.Linear) or isinstance(m, MaskedConv):\n init.xavier_normal_(m.weight)\n\n\n_AFFINE = True\n\n\nclass LambdaLayer(nn.Module):\n def __init__(self, lambd):\n super(LambdaLayer, self).__init__()\n self.lambd = lambd\n\n def forward(self, x):\n return self.lambd(x)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, in_planes, planes, stride=1):\n super(BasicBlock, self).__init__()\n self.conv1 = MaskedConv(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes, affine=_AFFINE)\n self.conv2 = MaskedConv(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes, affine=_AFFINE)\n\n self.downsample = None\n self.bn3 = None\n if stride != 1 or in_planes != planes:\n self.downsample = nn.Sequential(\n MaskedConv(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False))\n self.bn3 = nn.BatchNorm2d(self.expansion * planes, affine=_AFFINE)\n\n def forward(self, x):\n # x: batch_size * in_c * h * w\n residual = x\n out = F.relu(self.bn1(self.conv1(x)))\n out = self.bn2(self.conv2(out))\n if self.downsample is not None:\n residual = self.bn3(self.downsample(x))\n out += residual\n out = F.relu(out)\n return out\n\n\nclass ResNet(nn.Module):\n def __init__(self, block, num_blocks, num_classes=10):\n super(ResNet, self).__init__()\n _outputs = [32, 64, 128]\n self.in_planes = _outputs[0]\n\n self.conv1 = MaskedConv(3, _outputs[0], kernel_size=3, stride=1, padding=1, bias=False)\n self.bn = nn.BatchNorm2d(_outputs[0], affine=_AFFINE)\n self.layer1 = self._make_layer(block, _outputs[0], num_blocks[0], stride=1)\n self.layer2 = self._make_layer(block, _outputs[1], num_blocks[1], stride=2)\n self.layer3 = self._make_layer(block, _outputs[2], num_blocks[2], stride=2)\n self.linear = nn.Linear(_outputs[2], num_classes)\n\n self.apply(_weights_init)\n\n def _make_layer(self, block, planes, num_blocks, stride):\n strides = [stride] + [1] * (num_blocks - 1)\n layers = []\n for stride in strides:\n layers.append(block(self.in_planes, planes, stride))\n self.in_planes = planes * block.expansion\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n out = F.relu(self.bn(self.conv1(x)))\n out = self.layer1(out)\n out = self.layer2(out)\n out = self.layer3(out)\n out = F.avg_pool2d(out, out.size()[3])\n out = out.view(out.size(0), -1)\n out = self.linear(out)\n return out\n\n\ndef resnet20(num_classes):\n return ResNet(BasicBlock, [3, 3, 3], num_classes=num_classes)\n\n\ndef resnet32(num_classes):\n return ResNet(BasicBlock, [5, 5, 5], num_classes=num_classes)\n\n\ndef resnet44(num_classes):\n return ResNet(BasicBlock, [7, 7, 7], num_classes=num_classes)\n\n\ndef resnet56(num_classes):\n return ResNet(BasicBlock, [9, 9, 9], num_classes=num_classes)\n\n\ndef resnet110(num_classes):\n return ResNet(BasicBlock, [18, 18, 18], num_classes=num_classes)\n\n\ndef resnet1202(num_classes):\n return ResNet(BasicBlock, [200, 200, 200], num_clases=num_classes)\n" ]
[ [ "torch.nn.Linear", "torch.nn.Sequential", "torch.nn.BatchNorm2d", "torch.nn.functional.relu", "torch.nn.init.xavier_normal_" ] ]
enwudz/pytracker
[ "e6648c40ecd68dbe995b0873af7ed6d438e32f95" ]
[ "npy2csv.py" ]
[ "## This is the NEWEST version (Aug 24,2020). It accommodates time \"gaps\" among the npy files that result from stopping and starting data collection.\n\n# Until Dec26,2020, its filename was \"testing.py\"\n\nimport numpy as np\nimport sys\nimport analysisTools\nfrom matplotlib import dates\n\nbinSize = 1\n\n# choose whether to get all of the data, or just those after a certain time\nif len(sys.argv) > 1:\n startData = sys.argv[1]\n csvFile = 'distances_' + str(binSize) + '_' + startData + '.csv'\n timeStampFile = 'distances_' + str(binSize) + '_' + startData + '.csv'\n\n data = analysisTools.loadDataFromStartTime(startData,'xy')\n\nelse:\n csvFile = 'distances_' + str(binSize) + '.csv'\n timeStampFile = 'timeStamps_' + str(binSize) + '.csv'\n # load all xy data\n data = analysisTools.loadData('xy')\n\n\n# split data at time gaps, if any\ndataChunks = analysisTools.getMatrixSubsets(data,analysisTools.checkDataForTimeGaps(data))\n\n# initialize empty containers for binnedData and binnedTime\nbinnedData = []\nbinnedTime = []\n\nfor i,data in enumerate(dataChunks):\n\n print('--> looking at chunk ' + str(i+1) + ' of ' + str(len(dataChunks)))\n # convert coordinates to distances\n d = analysisTools.convertXYDataToDistances(data)\n\n '''\n bin data\n analysisTools.binData takes two arguments:\n (1) the data to be binned (including timestamps)\n (2) the binSize in seconds\n for 1 minute bins, binSize = 60\n for 10 minutes bins, binSize = 600\n\n analysisTools.binData returns two outputs\n (1) binned data, (2) binned time vector\n '''\n\n bd,bt = analysisTools.binData(d,binSize)\n print(' data in this chunk',np.shape(bd)) # could comment these out\n print(' times in this chunk',np.shape(bt)) # could comment these out\n\n if len(binnedData) == 0:\n binnedData = bd\n binnedTime = bt\n else:\n binnedData = np.vstack((binnedData,bd))\n binnedTime = np.hstack((binnedTime,bt))\n\n# save the binned distances data to a .csv file\nprint(' saving data to %s . . . ' % csvFile)\nnp.savetxt(csvFile, binnedData, delimiter=',', fmt = '%1.2f' ,newline='\\n')\n\n# convert time to yyyy-mm-dd hh:mm:ss format\nbinnedTime = [dates.num2date(x).strftime('%Y-%m-%d %H:%M:%S') for x in binnedTime]\n\n# save the binned time vector to a .csv file\nprint(' saving timestamps to %s . . . ' % timeStampFile)\nwith open(timeStampFile,'w') as f:\n\tfor t in binnedTime:\n\t\tf.write('%s\\n' % t)\n" ]
[ [ "numpy.savetxt", "numpy.shape", "matplotlib.dates.num2date", "numpy.hstack", "numpy.vstack" ] ]
erinfry6/machine-learning-engineering-for-production-public
[ "22af96d2cba8f8021ed08c3b88f3c0d8fa51a01e" ]
[ "course4/week3-ungraded-labs/C4_W3_Lab_4_Github_Actions/app/main.py" ]
[ "import pickle\nimport numpy as np\nfrom typing import List\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel, conlist\n\n# test \n\napp = FastAPI(title=\"Predicting Wine Class with batching\")\n\n# Open classifier in global scope\nwith open(\"models/wine-95.pkl\", \"rb\") as file:\n clf = pickle.load(file)\n\n\nclass Wine(BaseModel):\n batches: List[conlist(item_type=float, min_items=13, max_items=13)]\n\n\[email protected](\"/predict\")\ndef predict(wine: Wine):\n batches = wine.batches\n np_batches = np.array(batches)\n pred = clf.predict(np_batches).tolist()\n return {\"Prediction\": pred}\n" ]
[ [ "numpy.array" ] ]
vishal1905/face-alignment
[ "5c2069aefdfbc028b37021542db68e5a2789db4d" ]
[ "face_alignment/api.py" ]
[ "import torch\r\nfrom enum import IntEnum\r\nfrom skimage import io\r\nimport numpy as np\r\nfrom distutils.version import LooseVersion\r\n\r\nfrom .utils import *\r\n\r\n\r\nclass LandmarksType(IntEnum):\r\n \"\"\"Enum class defining the type of landmarks to detect.\r\n\r\n ``_2D`` - the detected points ``(x,y)`` are detected in a 2D space and follow the visible contour of the face\r\n ``_2halfD`` - this points represent the projection of the 3D points into 3D\r\n ``_3D`` - detect the points ``(x,y,z)``` in a 3D space\r\n\r\n \"\"\"\r\n _2D = 1\r\n _2halfD = 2\r\n _3D = 3\r\n\r\n\r\nclass NetworkSize(IntEnum):\r\n # TINY = 1\r\n # SMALL = 2\r\n # MEDIUM = 3\r\n LARGE = 4\r\n\r\n\r\ndefault_model_urls = {\r\n '2DFAN-4': 'https://www.adrianbulat.com/downloads/python-fan/2DFAN4-cd938726ad.zip',\r\n '3DFAN-4': 'https://www.adrianbulat.com/downloads/python-fan/3DFAN4-4a694010b9.zip',\r\n 'depth': 'https://www.adrianbulat.com/downloads/python-fan/depth-6c4283c0e0.zip',\r\n}\r\n\r\nmodels_urls = {\r\n '1.6': {\r\n '2DFAN-4': 'https://www.adrianbulat.com/downloads/python-fan/2DFAN4_1.6-c827573f02.zip',\r\n '3DFAN-4': 'https://www.adrianbulat.com/downloads/python-fan/3DFAN4_1.6-ec5cf40a1d.zip',\r\n 'depth': 'https://www.adrianbulat.com/downloads/python-fan/depth_1.6-2aa3f18772.zip',\r\n },\r\n '1.5': {\r\n '2DFAN-4': 'https://www.adrianbulat.com/downloads/python-fan/2DFAN4_1.5-a60332318a.zip',\r\n '3DFAN-4': 'https://www.adrianbulat.com/downloads/python-fan/3DFAN4_1.5-176570af4d.zip',\r\n 'depth': 'https://www.adrianbulat.com/downloads/python-fan/depth_1.5-bc10f98e39.zip',\r\n },\r\n}\r\n\r\n\r\nclass FaceAlignment:\r\n def __init__(self, landmarks_type, network_size=NetworkSize.LARGE,\r\n device='cuda', flip_input=False, face_detector='sfd', verbose=False):\r\n self.device = device\r\n self.flip_input = flip_input\r\n self.landmarks_type = landmarks_type\r\n self.verbose = verbose\r\n\r\n if LooseVersion(torch.__version__) < LooseVersion('1.5.0'):\r\n raise ImportError(f'Unsupported pytorch version detected. Minimum supported version of pytorch: 1.5.0')\r\n\r\n network_size = int(network_size)\r\n pytorch_version = torch.__version__\r\n if 'dev' in pytorch_version:\r\n pytorch_version = pytorch_version.rsplit('.', 2)[0]\r\n else:\r\n pytorch_version = pytorch_version.rsplit('.', 1)[0]\r\n\r\n if 'cuda' in device:\r\n torch.backends.cudnn.benchmark = True\r\n\r\n # Get the face detector\r\n face_detector_module = __import__('face_alignment.detection.' + face_detector,\r\n globals(), locals(), [face_detector], 0)\r\n self.face_detector = face_detector_module.FaceDetector(device=device, verbose=verbose)\r\n\r\n # Initialise the face alignemnt networks\r\n if landmarks_type == LandmarksType._2D:\r\n network_name = '2DFAN-' + str(network_size)\r\n else:\r\n network_name = '3DFAN-' + str(network_size)\r\n self.face_alignment_net = torch.jit.load(\r\n load_file_from_url(models_urls.get(pytorch_version, default_model_urls)[network_name]))\r\n\r\n self.face_alignment_net.to(device)\r\n self.face_alignment_net.eval()\r\n\r\n # Initialiase the depth prediciton network\r\n if landmarks_type == LandmarksType._3D:\r\n self.depth_prediciton_net = torch.jit.load(\r\n load_file_from_url(models_urls.get(pytorch_version, default_model_urls)['depth']))\r\n\r\n self.depth_prediciton_net.to(device)\r\n self.depth_prediciton_net.eval()\r\n\r\n def get_landmarks(self, image_or_path, detected_faces=None):\r\n \"\"\"Deprecated, please use get_landmarks_from_image\r\n\r\n Arguments:\r\n image_or_path {string or numpy.array or torch.tensor} -- The input image or path to it.\r\n\r\n Keyword Arguments:\r\n detected_faces {list of numpy.array} -- list of bounding boxes, one for each face found\r\n in the image (default: {None})\r\n \"\"\"\r\n return self.get_landmarks_from_image(image_or_path, detected_faces)\r\n\r\n @torch.no_grad()\r\n def get_landmarks_from_image(self, image_or_path, detected_faces=None):\r\n \"\"\"Predict the landmarks for each face present in the image.\r\n\r\n This function predicts a set of 68 2D or 3D images, one for each image present.\r\n If detect_faces is None the method will also run a face detector.\r\n\r\n Arguments:\r\n image_or_path {string or numpy.array or torch.tensor} -- The input image or path to it.\r\n\r\n Keyword Arguments:\r\n detected_faces {list of numpy.array} -- list of bounding boxes, one for each face found\r\n in the image (default: {None})\r\n \"\"\"\r\n image = get_image(image_or_path)\r\n\r\n if detected_faces is None:\r\n detected_faces = self.face_detector.detect_from_image(image.copy())\r\n\r\n if len(detected_faces) == 0:\r\n print(\"Warning: No faces were detected.\")\r\n return None\r\n\r\n landmarks = []\r\n for i, d in enumerate(detected_faces):\r\n center = torch.tensor(\r\n [d[2] - (d[2] - d[0]) / 2.0, d[3] - (d[3] - d[1]) / 2.0])\r\n center[1] = center[1] - (d[3] - d[1]) * 0.12\r\n scale = (d[2] - d[0] + d[3] - d[1]) / self.face_detector.reference_scale\r\n\r\n inp = crop(image, center, scale)\r\n inp = torch.from_numpy(inp.transpose(\r\n (2, 0, 1))).float()\r\n\r\n inp = inp.to(self.device)\r\n inp.div_(255.0).unsqueeze_(0)\r\n\r\n out = self.face_alignment_net(inp).detach()\r\n if self.flip_input:\r\n out += flip(self.face_alignment_net(flip(inp)).detach(), is_label=True)\r\n out = out.cpu().numpy()\r\n\r\n pts, pts_img = get_preds_fromhm(out, center.numpy(), scale)\r\n pts, pts_img = torch.from_numpy(pts), torch.from_numpy(pts_img)\r\n pts, pts_img = pts.view(68, 2) * 4, pts_img.view(68, 2)\r\n\r\n if self.landmarks_type == LandmarksType._3D:\r\n heatmaps = np.zeros((68, 256, 256), dtype=np.float32)\r\n for i in range(68):\r\n if pts[i, 0] > 0 and pts[i, 1] > 0:\r\n heatmaps[i] = draw_gaussian(\r\n heatmaps[i], pts[i], 2)\r\n heatmaps = torch.from_numpy(\r\n heatmaps).unsqueeze_(0)\r\n\r\n heatmaps = heatmaps.to(self.device)\r\n depth_pred = self.depth_prediciton_net(\r\n torch.cat((inp, heatmaps), 1)).data.cpu().view(68, 1)\r\n pts_img = torch.cat(\r\n (pts_img, depth_pred * (1.0 / (256.0 / (200.0 * scale)))), 1)\r\n\r\n landmarks.append(pts_img.numpy())\r\n\r\n return landmarks\r\n\r\n @torch.no_grad()\r\n def get_landmarks_from_batch(self, image_batch, detected_faces=None):\r\n \"\"\"Predict the landmarks for each face present in the image.\r\n\r\n This function predicts a set of 68 2D or 3D images, one for each image in a batch in parallel.\r\n If detect_faces is None the method will also run a face detector.\r\n\r\n Arguments:\r\n image_batch {torch.tensor} -- The input images batch\r\n\r\n Keyword Arguments:\r\n detected_faces {list of numpy.array} -- list of bounding boxes, one for each face found\r\n in the image (default: {None})\r\n \"\"\"\r\n\r\n if detected_faces is None:\r\n detected_faces = self.face_detector.detect_from_batch(image_batch)\r\n\r\n if len(detected_faces) == 0:\r\n print(\"Warning: No faces were detected.\")\r\n return None\r\n\r\n landmarks = []\r\n # A batch for each frame\r\n for i, faces in enumerate(detected_faces):\r\n landmark_set = self.get_landmarks_from_image(\r\n image_batch[i].cpu().numpy().transpose(1, 2, 0),\r\n detected_faces=faces\r\n )\r\n # Bacward compatibility\r\n if landmark_set is not None:\r\n landmark_set = np.concatenate(landmark_set, axis=0)\r\n else:\r\n landmark_set = []\r\n landmarks.append(landmark_set)\r\n return landmarks\r\n\r\n def get_landmarks_from_directory(self, path, extensions=['.jpg', '.png'], recursive=True, show_progress_bar=True):\r\n detected_faces = self.face_detector.detect_from_directory(path, extensions, recursive, show_progress_bar)\r\n\r\n predictions = {}\r\n for image_path, bounding_boxes in detected_faces.items():\r\n image = io.imread(image_path)\r\n preds = self.get_landmarks_from_image(image, bounding_boxes)\r\n predictions[image_path] = preds\r\n\r\n return predictions\r\n" ]
[ [ "numpy.concatenate", "torch.cat", "numpy.zeros", "torch.no_grad", "torch.from_numpy", "torch.tensor" ] ]
wkitlasten/flopy
[ "e77536f43cb6e01ba54ac2a9f047925c188b1486" ]
[ "flopy/utils/reference.py" ]
[ "\"\"\"\nModule spatial referencing for flopy model objects\n\n\"\"\"\nimport json\nimport numpy as np\nimport os\nimport warnings\n\nfrom collections import OrderedDict\n\n__all__ = [\"TemporalReference\"]\n# all other classes and methods in this module are deprecated\n\n# web address of spatial reference dot org\nsrefhttp = \"https://spatialreference.org\"\n\n\nclass SpatialReference:\n \"\"\"\n a class to locate a structured model grid in x-y space\n\n .. deprecated:: 3.2.11\n This class will be removed in version 3.3.5. Use\n :py:class:`flopy.discretization.structuredgrid.StructuredGrid` instead.\n\n Parameters\n ----------\n\n delr : numpy ndarray\n the model discretization delr vector\n (An array of spacings along a row)\n delc : numpy ndarray\n the model discretization delc vector\n (An array of spacings along a column)\n lenuni : int\n the length units flag from the discretization package\n (default 2)\n xul : float\n the x coordinate of the upper left corner of the grid\n Enter either xul and yul or xll and yll.\n yul : float\n the y coordinate of the upper left corner of the grid\n Enter either xul and yul or xll and yll.\n xll : float\n the x coordinate of the lower left corner of the grid\n Enter either xul and yul or xll and yll.\n yll : float\n the y coordinate of the lower left corner of the grid\n Enter either xul and yul or xll and yll.\n rotation : float\n the counter-clockwise rotation (in degrees) of the grid\n\n proj4_str: str\n a PROJ4 string that identifies the grid in space. warning: case\n sensitive!\n\n units : string\n Units for the grid. Must be either feet or meters\n\n epsg : int\n EPSG code that identifies the grid in space. Can be used in lieu of\n proj4. PROJ4 attribute will auto-populate if there is an internet\n connection(via get_proj4 method).\n See https://www.epsg-registry.org/ or spatialreference.org\n\n length_multiplier : float\n multiplier to convert model units to spatial reference units.\n delr and delc above will be multiplied by this value. (default=1.)\n\n Attributes\n ----------\n xedge : ndarray\n array of column edges\n\n yedge : ndarray\n array of row edges\n\n xgrid : ndarray\n numpy meshgrid of xedges\n\n ygrid : ndarray\n numpy meshgrid of yedges\n\n xcenter : ndarray\n array of column centers\n\n ycenter : ndarray\n array of row centers\n\n xcentergrid : ndarray\n numpy meshgrid of column centers\n\n ycentergrid : ndarray\n numpy meshgrid of row centers\n\n vertices : 1D array\n 1D array of cell vertices for whole grid in C-style (row-major) order\n (same as np.ravel())\n\n\n Notes\n -----\n\n xul and yul can be explicitly (re)set after SpatialReference\n instantiation, but only before any of the other attributes and methods are\n accessed\n\n \"\"\"\n\n xul, yul = None, None\n xll, yll = None, None\n rotation = 0.0\n length_multiplier = 1.0\n origin_loc = \"ul\" # or ll\n\n defaults = {\n \"xul\": None,\n \"yul\": None,\n \"rotation\": 0.0,\n \"proj4_str\": None,\n \"units\": None,\n \"lenuni\": 2,\n \"length_multiplier\": None,\n \"source\": \"defaults\",\n }\n\n lenuni_values = {\"undefined\": 0, \"feet\": 1, \"meters\": 2, \"centimeters\": 3}\n lenuni_text = {v: k for k, v in lenuni_values.items()}\n\n def __init__(\n self,\n delr=np.array([]),\n delc=np.array([]),\n lenuni=2,\n xul=None,\n yul=None,\n xll=None,\n yll=None,\n rotation=0.0,\n proj4_str=None,\n epsg=None,\n prj=None,\n units=None,\n length_multiplier=None,\n ):\n warnings.warn(\n \"SpatialReference has been deprecated and will be removed in \"\n \"version 3.3.5. Use StructuredGrid instead.\",\n category=DeprecationWarning,\n )\n\n for delrc in [delr, delc]:\n if isinstance(delrc, float) or isinstance(delrc, int):\n msg = (\n \"delr and delcs must be an array or sequences equal in \"\n \"length to the number of rows/columns.\"\n )\n raise TypeError(msg)\n\n self.delc = np.atleast_1d(np.array(delc)).astype(\n np.float64\n ) # * length_multiplier\n self.delr = np.atleast_1d(np.array(delr)).astype(\n np.float64\n ) # * length_multiplier\n\n if self.delr.sum() == 0 or self.delc.sum() == 0:\n if xll is None or yll is None:\n msg = (\n \"Warning: no grid spacing or lower-left corner \"\n \"supplied. Setting the offset with xul, yul requires \"\n \"arguments for delr and delc. Origin will be set to \"\n \"zero.\"\n )\n print(msg)\n xll, yll = 0, 0\n xul, yul = None, None\n\n self._lenuni = lenuni\n self._proj4_str = proj4_str\n\n self._epsg = epsg\n if epsg is not None:\n self._proj4_str = getproj4(self._epsg)\n self.prj = prj\n self._wkt = None\n self.crs = crs(prj=prj, epsg=epsg)\n\n self.supported_units = [\"feet\", \"meters\"]\n self._units = units\n self._length_multiplier = length_multiplier\n self._reset()\n self.set_spatialreference(xul, yul, xll, yll, rotation)\n\n @property\n def xll(self):\n if self.origin_loc == \"ll\":\n xll = self._xll if self._xll is not None else 0.0\n elif self.origin_loc == \"ul\":\n # calculate coords for lower left corner\n xll = self._xul - (\n np.sin(self.theta) * self.yedge[0] * self.length_multiplier\n )\n return xll\n\n @property\n def yll(self):\n if self.origin_loc == \"ll\":\n yll = self._yll if self._yll is not None else 0.0\n elif self.origin_loc == \"ul\":\n # calculate coords for lower left corner\n yll = self._yul - (\n np.cos(self.theta) * self.yedge[0] * self.length_multiplier\n )\n return yll\n\n @property\n def xul(self):\n if self.origin_loc == \"ll\":\n # calculate coords for upper left corner\n xul = self._xll + (\n np.sin(self.theta) * self.yedge[0] * self.length_multiplier\n )\n if self.origin_loc == \"ul\":\n # calculate coords for lower left corner\n xul = self._xul if self._xul is not None else 0.0\n return xul\n\n @property\n def yul(self):\n if self.origin_loc == \"ll\":\n # calculate coords for upper left corner\n yul = self._yll + (\n np.cos(self.theta) * self.yedge[0] * self.length_multiplier\n )\n\n if self.origin_loc == \"ul\":\n # calculate coords for lower left corner\n yul = self._yul if self._yul is not None else 0.0\n return yul\n\n @property\n def proj4_str(self):\n proj4_str = None\n if self._proj4_str is not None:\n if \"epsg\" in self._proj4_str.lower():\n proj4_str = self._proj4_str\n # set the epsg if proj4 specifies it\n tmp = [\n i for i in self._proj4_str.split() if \"epsg\" in i.lower()\n ]\n self._epsg = int(tmp[0].split(\":\")[1])\n else:\n proj4_str = self._proj4_str\n elif self.epsg is not None:\n proj4_str = \"epsg:{}\".format(self.epsg)\n return proj4_str\n\n @property\n def epsg(self):\n # don't reset the proj4 string here\n # because proj4 attribute may already be populated\n # (with more details than getproj4 would return)\n # instead reset proj4 when epsg is set\n # (on init or setattr)\n return self._epsg\n\n @property\n def wkt(self):\n if self._wkt is None:\n if self.prj is not None:\n with open(self.prj) as src:\n wkt = src.read()\n elif self.epsg is not None:\n wkt = getprj(self.epsg)\n else:\n return None\n return wkt\n else:\n return self._wkt\n\n @property\n def lenuni(self):\n return self._lenuni\n\n def _parse_units_from_proj4(self):\n units = None\n try:\n # need this because preserve_units doesn't seem to be\n # working for complex proj4 strings. So if an\n # epsg code was passed, we have no choice, but if a\n # proj4 string was passed, we can just parse it\n if \"EPSG\" in self.proj4_str.upper():\n import pyproj\n\n crs = pyproj.Proj(self.proj4_str, preserve_units=True)\n proj_str = crs.srs\n else:\n proj_str = self.proj4_str\n # http://proj4.org/parameters.html#units\n # from proj4 source code\n # \"us-ft\", \"0.304800609601219\", \"U.S. Surveyor's Foot\",\n # \"ft\", \"0.3048\", \"International Foot\",\n if \"units=m\" in proj_str:\n units = \"meters\"\n elif (\n \"units=ft\" in proj_str\n or \"units=us-ft\" in proj_str\n or \"to_meter=0.3048\" in proj_str\n ):\n units = \"feet\"\n return units\n except:\n if self.proj4_str is not None:\n print(\n \" could not parse units from {}\".format(self.proj4_str)\n )\n\n @property\n def units(self):\n if self._units is not None:\n units = self._units.lower()\n else:\n units = self._parse_units_from_proj4()\n if units is None:\n # print(\"warning: assuming SpatialReference units are meters\")\n units = \"meters\"\n assert units in self.supported_units\n return units\n\n @property\n def length_multiplier(self):\n \"\"\"\n Attempt to identify multiplier for converting from\n model units to sr units, defaulting to 1.\n \"\"\"\n lm = None\n if self._length_multiplier is not None:\n lm = self._length_multiplier\n else:\n if self.model_length_units == \"feet\":\n if self.units == \"meters\":\n lm = 0.3048\n elif self.units == \"feet\":\n lm = 1.0\n elif self.model_length_units == \"meters\":\n if self.units == \"feet\":\n lm = 1 / 0.3048\n elif self.units == \"meters\":\n lm = 1.0\n elif self.model_length_units == \"centimeters\":\n if self.units == \"meters\":\n lm = 1 / 100.0\n elif self.units == \"feet\":\n lm = 1 / 30.48\n else: # model units unspecified; default to 1\n lm = 1.0\n return lm\n\n @property\n def model_length_units(self):\n return self.lenuni_text[self.lenuni]\n\n @property\n def bounds(self):\n \"\"\"\n Return bounding box in shapely order.\n \"\"\"\n xmin, xmax, ymin, ymax = self.get_extent()\n return xmin, ymin, xmax, ymax\n\n @classmethod\n def load(cls, namefile=None, reffile=\"usgs.model.reference\"):\n \"\"\"\n Attempts to load spatial reference information from\n the following files (in order):\n 1) usgs.model.reference\n 2) NAM file (header comment)\n 3) SpatialReference.default dictionary\n \"\"\"\n reffile = os.path.join(os.path.split(namefile)[0], reffile)\n d = SpatialReference.read_usgs_model_reference_file(reffile)\n if d is not None:\n return d\n d = SpatialReference.attribs_from_namfile_header(namefile)\n if d is not None:\n return d\n else:\n return SpatialReference.defaults\n\n @staticmethod\n def attribs_from_namfile_header(namefile):\n # check for reference info in the nam file header\n d = SpatialReference.defaults.copy()\n d[\"source\"] = \"namfile\"\n if namefile is None:\n return None\n header = []\n with open(namefile, \"r\") as f:\n for line in f:\n if not line.startswith(\"#\"):\n break\n header.extend(line.strip().replace(\"#\", \"\").split(\";\"))\n\n for item in header:\n if \"xul\" in item.lower():\n try:\n d[\"xul\"] = float(item.split(\":\")[1])\n except:\n print(\" could not parse xul \" + \"in {}\".format(namefile))\n elif \"yul\" in item.lower():\n try:\n d[\"yul\"] = float(item.split(\":\")[1])\n except:\n print(\" could not parse yul \" + \"in {}\".format(namefile))\n elif \"rotation\" in item.lower():\n try:\n d[\"rotation\"] = float(item.split(\":\")[1])\n except:\n print(\n \" could not parse rotation \"\n + \"in {}\".format(namefile)\n )\n elif \"proj4_str\" in item.lower():\n try:\n proj4_str = \":\".join(item.split(\":\")[1:]).strip()\n if proj4_str.lower() == \"none\":\n proj4_str = None\n d[\"proj4_str\"] = proj4_str\n except:\n print(\n \" could not parse proj4_str \"\n + \"in {}\".format(namefile)\n )\n elif \"start\" in item.lower():\n try:\n d[\"start_datetime\"] = item.split(\":\")[1].strip()\n except:\n print(\n \" could not parse start \" + \"in {}\".format(namefile)\n )\n\n # spatial reference length units\n elif \"units\" in item.lower():\n d[\"units\"] = item.split(\":\")[1].strip()\n # model length units\n elif \"lenuni\" in item.lower():\n d[\"lenuni\"] = int(item.split(\":\")[1].strip())\n # multiplier for converting from model length units to sr length units\n elif \"length_multiplier\" in item.lower():\n d[\"length_multiplier\"] = float(item.split(\":\")[1].strip())\n return d\n\n @staticmethod\n def read_usgs_model_reference_file(reffile=\"usgs.model.reference\"):\n \"\"\"\n read spatial reference info from the usgs.model.reference file\n https://water.usgs.gov/ogw/policy/gw-model/modelers-setup.html\n \"\"\"\n\n ITMUNI = {\n 0: \"undefined\",\n 1: \"seconds\",\n 2: \"minutes\",\n 3: \"hours\",\n 4: \"days\",\n 5: \"years\",\n }\n itmuni_values = {v: k for k, v in ITMUNI.items()}\n\n d = SpatialReference.defaults.copy()\n d[\"source\"] = \"usgs.model.reference\"\n # discard default to avoid confusion with epsg code if entered\n d.pop(\"proj4_str\")\n if os.path.exists(reffile):\n with open(reffile) as fref:\n for line in fref:\n if len(line) > 1:\n if line.strip()[0] != \"#\":\n info = line.strip().split(\"#\")[0].split()\n if len(info) > 1:\n d[info[0].lower()] = \" \".join(info[1:])\n d[\"xul\"] = float(d[\"xul\"])\n d[\"yul\"] = float(d[\"yul\"])\n d[\"rotation\"] = float(d[\"rotation\"])\n\n # convert the model.reference text to a lenuni value\n # (these are the model length units)\n if \"length_units\" in d.keys():\n d[\"lenuni\"] = SpatialReference.lenuni_values[d[\"length_units\"]]\n if \"time_units\" in d.keys():\n d[\"itmuni\"] = itmuni_values[d[\"time_units\"]]\n if \"start_date\" in d.keys():\n start_datetime = d.pop(\"start_date\")\n if \"start_time\" in d.keys():\n start_datetime += \" {}\".format(d.pop(\"start_time\"))\n d[\"start_datetime\"] = start_datetime\n if \"epsg\" in d.keys():\n try:\n d[\"epsg\"] = int(d[\"epsg\"])\n except Exception as e:\n raise Exception(\n \"error reading epsg code from file:\\n\" + str(e)\n )\n # this prioritizes epsg over proj4 if both are given\n # (otherwise 'proj4' entry will be dropped below)\n elif \"proj4\" in d.keys():\n d[\"proj4_str\"] = d[\"proj4\"]\n\n # drop any other items that aren't used in sr class\n d = {\n k: v\n for k, v in d.items()\n if k.lower() in SpatialReference.defaults.keys()\n or k.lower() in {\"epsg\", \"start_datetime\", \"itmuni\", \"source\"}\n }\n return d\n else:\n return None\n\n def __setattr__(self, key, value):\n reset = True\n if key == \"delr\":\n super().__setattr__(\"delr\", np.atleast_1d(np.array(value)))\n elif key == \"delc\":\n super().__setattr__(\"delc\", np.atleast_1d(np.array(value)))\n elif key == \"xul\":\n super().__setattr__(\"_xul\", float(value))\n self.origin_loc = \"ul\"\n elif key == \"yul\":\n super().__setattr__(\"_yul\", float(value))\n self.origin_loc = \"ul\"\n elif key == \"xll\":\n super().__setattr__(\"_xll\", float(value))\n self.origin_loc = \"ll\"\n elif key == \"yll\":\n super().__setattr__(\"_yll\", float(value))\n self.origin_loc = \"ll\"\n elif key == \"length_multiplier\":\n super().__setattr__(\"_length_multiplier\", float(value))\n # self.set_origin(xul=self.xul, yul=self.yul, xll=self.xll,\n # yll=self.yll)\n elif key == \"rotation\":\n super().__setattr__(\"rotation\", float(value))\n # self.set_origin(xul=self.xul, yul=self.yul, xll=self.xll,\n # yll=self.yll)\n elif key == \"lenuni\":\n super().__setattr__(\"_lenuni\", int(value))\n # self.set_origin(xul=self.xul, yul=self.yul, xll=self.xll,\n # yll=self.yll)\n elif key == \"units\":\n value = value.lower()\n assert value in self.supported_units\n super().__setattr__(\"_units\", value)\n elif key == \"proj4_str\":\n super().__setattr__(\"_proj4_str\", value)\n # reset the units and epsg\n units = self._parse_units_from_proj4()\n if units is not None:\n self._units = units\n self._epsg = None\n elif key == \"epsg\":\n super().__setattr__(\"_epsg\", value)\n # reset the units and proj4\n self._units = None\n self._proj4_str = getproj4(self._epsg)\n self.crs = crs(epsg=value)\n elif key == \"prj\":\n super().__setattr__(\"prj\", value)\n # translation to proj4 strings in crs class not robust yet\n # leave units and proj4 alone for now.\n self.crs = crs(prj=value, epsg=self.epsg)\n else:\n super().__setattr__(key, value)\n reset = False\n if reset:\n self._reset()\n\n def reset(self, **kwargs):\n for key, value in kwargs.items():\n setattr(self, key, value)\n return\n\n def _reset(self):\n self._xgrid = None\n self._ygrid = None\n self._ycentergrid = None\n self._xcentergrid = None\n self._vertices = None\n return\n\n @property\n def nrow(self):\n return self.delc.shape[0]\n\n @property\n def ncol(self):\n return self.delr.shape[0]\n\n def __eq__(self, other):\n if not isinstance(other, SpatialReference):\n return False\n if other.xul != self.xul:\n return False\n if other.yul != self.yul:\n return False\n if other.rotation != self.rotation:\n return False\n if other.proj4_str != self.proj4_str:\n return False\n return True\n\n @classmethod\n def from_namfile(cls, namefile):\n attribs = SpatialReference.attribs_from_namfile_header(namefile)\n try:\n attribs.pop(\"start_datetime\")\n except:\n print(\" could not remove start_datetime\")\n\n return cls(**attribs)\n\n @classmethod\n def from_gridspec(cls, gridspec_file, lenuni=0):\n f = open(gridspec_file, \"r\")\n raw = f.readline().strip().split()\n nrow = int(raw[0])\n ncol = int(raw[1])\n raw = f.readline().strip().split()\n xul, yul, rot = float(raw[0]), float(raw[1]), float(raw[2])\n delr = []\n j = 0\n while j < ncol:\n raw = f.readline().strip().split()\n for r in raw:\n if \"*\" in r:\n rraw = r.split(\"*\")\n for n in range(int(rraw[0])):\n delr.append(float(rraw[1]))\n j += 1\n else:\n delr.append(float(r))\n j += 1\n delc = []\n i = 0\n while i < nrow:\n raw = f.readline().strip().split()\n for r in raw:\n if \"*\" in r:\n rraw = r.split(\"*\")\n for n in range(int(rraw[0])):\n delc.append(float(rraw[1]))\n i += 1\n else:\n delc.append(float(r))\n i += 1\n f.close()\n return cls(\n np.array(delr),\n np.array(delc),\n lenuni,\n xul=xul,\n yul=yul,\n rotation=rot,\n )\n\n @property\n def attribute_dict(self):\n return {\n \"xul\": self.xul,\n \"yul\": self.yul,\n \"rotation\": self.rotation,\n \"proj4_str\": self.proj4_str,\n }\n\n def set_spatialreference(\n self, xul=None, yul=None, xll=None, yll=None, rotation=0.0\n ):\n \"\"\"\n set spatial reference - can be called from model instance\n\n \"\"\"\n if xul is not None and xll is not None:\n msg = (\n \"Both xul and xll entered. Please enter either xul, yul or \"\n \"xll, yll.\"\n )\n raise ValueError(msg)\n if yul is not None and yll is not None:\n msg = (\n \"Both yul and yll entered. Please enter either xul, yul or \"\n \"xll, yll.\"\n )\n raise ValueError(msg)\n # set the origin priority based on the left corner specified\n # (the other left corner will be calculated). If none are specified\n # then default to upper left\n if xul is None and yul is None and xll is None and yll is None:\n self.origin_loc = \"ul\"\n xul = 0.0\n yul = self.delc.sum()\n elif xll is not None:\n self.origin_loc = \"ll\"\n else:\n self.origin_loc = \"ul\"\n\n self.rotation = rotation\n self._xll = xll if xll is not None else 0.0\n self._yll = yll if yll is not None else 0.0\n self._xul = xul if xul is not None else 0.0\n self._yul = yul if yul is not None else 0.0\n # self.set_origin(xul, yul, xll, yll)\n return\n\n def __repr__(self):\n s = \"xul:{0:<.10G}; yul:{1:<.10G}; rotation:{2:<G}; \".format(\n self.xul, self.yul, self.rotation\n )\n s += \"proj4_str:{0}; \".format(self.proj4_str)\n s += \"units:{0}; \".format(self.units)\n s += \"lenuni:{0}; \".format(self.lenuni)\n s += \"length_multiplier:{}\".format(self.length_multiplier)\n return s\n\n def set_origin(self, xul=None, yul=None, xll=None, yll=None):\n if self.origin_loc == \"ll\":\n # calculate coords for upper left corner\n self._xll = xll if xll is not None else 0.0\n self.yll = yll if yll is not None else 0.0\n self.xul = self._xll + (\n np.sin(self.theta) * self.yedge[0] * self.length_multiplier\n )\n self.yul = self.yll + (\n np.cos(self.theta) * self.yedge[0] * self.length_multiplier\n )\n\n if self.origin_loc == \"ul\":\n # calculate coords for lower left corner\n self.xul = xul if xul is not None else 0.0\n self.yul = yul if yul is not None else 0.0\n self._xll = self.xul - (\n np.sin(self.theta) * self.yedge[0] * self.length_multiplier\n )\n self.yll = self.yul - (\n np.cos(self.theta) * self.yedge[0] * self.length_multiplier\n )\n self._reset()\n return\n\n @property\n def theta(self):\n return -self.rotation * np.pi / 180.0\n\n @property\n def xedge(self):\n return self.get_xedge_array()\n\n @property\n def yedge(self):\n return self.get_yedge_array()\n\n @property\n def xgrid(self):\n if self._xgrid is None:\n self._set_xygrid()\n return self._xgrid\n\n @property\n def ygrid(self):\n if self._ygrid is None:\n self._set_xygrid()\n return self._ygrid\n\n @property\n def xcenter(self):\n return self.get_xcenter_array()\n\n @property\n def ycenter(self):\n return self.get_ycenter_array()\n\n @property\n def ycentergrid(self):\n if self._ycentergrid is None:\n self._set_xycentergrid()\n return self._ycentergrid\n\n @property\n def xcentergrid(self):\n if self._xcentergrid is None:\n self._set_xycentergrid()\n return self._xcentergrid\n\n def _set_xycentergrid(self):\n self._xcentergrid, self._ycentergrid = np.meshgrid(\n self.xcenter, self.ycenter\n )\n self._xcentergrid, self._ycentergrid = self.transform(\n self._xcentergrid, self._ycentergrid\n )\n\n def _set_xygrid(self):\n self._xgrid, self._ygrid = np.meshgrid(self.xedge, self.yedge)\n self._xgrid, self._ygrid = self.transform(self._xgrid, self._ygrid)\n\n @staticmethod\n def rotate(x, y, theta, xorigin=0.0, yorigin=0.0):\n \"\"\"\n Given x and y array-like values calculate the rotation about an\n arbitrary origin and then return the rotated coordinates. theta is in\n degrees.\n\n \"\"\"\n # jwhite changed on Oct 11 2016 - rotation is now positive CCW\n # theta = -theta * np.pi / 180.\n theta = theta * np.pi / 180.0\n\n xrot = (\n xorigin\n + np.cos(theta) * (x - xorigin)\n - np.sin(theta) * (y - yorigin)\n )\n yrot = (\n yorigin\n + np.sin(theta) * (x - xorigin)\n + np.cos(theta) * (y - yorigin)\n )\n return xrot, yrot\n\n def transform(self, x, y, inverse=False):\n \"\"\"\n Given x and y array-like values, apply rotation, scale and offset,\n to convert them from model coordinates to real-world coordinates.\n \"\"\"\n if isinstance(x, list):\n x = np.array(x)\n y = np.array(y)\n if not np.isscalar(x):\n x, y = x.copy(), y.copy()\n\n if not inverse:\n x *= self.length_multiplier\n y *= self.length_multiplier\n x += self.xll\n y += self.yll\n x, y = SpatialReference.rotate(\n x, y, theta=self.rotation, xorigin=self.xll, yorigin=self.yll\n )\n else:\n x, y = SpatialReference.rotate(\n x, y, -self.rotation, self.xll, self.yll\n )\n x -= self.xll\n y -= self.yll\n x /= self.length_multiplier\n y /= self.length_multiplier\n return x, y\n\n def get_extent(self):\n \"\"\"\n Get the extent of the rotated and offset grid\n\n Return (xmin, xmax, ymin, ymax)\n\n \"\"\"\n x0 = self.xedge[0]\n x1 = self.xedge[-1]\n y0 = self.yedge[0]\n y1 = self.yedge[-1]\n\n # upper left point\n x0r, y0r = self.transform(x0, y0)\n\n # upper right point\n x1r, y1r = self.transform(x1, y0)\n\n # lower right point\n x2r, y2r = self.transform(x1, y1)\n\n # lower left point\n x3r, y3r = self.transform(x0, y1)\n\n xmin = min(x0r, x1r, x2r, x3r)\n xmax = max(x0r, x1r, x2r, x3r)\n ymin = min(y0r, y1r, y2r, y3r)\n ymax = max(y0r, y1r, y2r, y3r)\n\n return (xmin, xmax, ymin, ymax)\n\n def get_grid_lines(self):\n \"\"\"\n Get the grid lines as a list\n\n \"\"\"\n xmin = self.xedge[0]\n xmax = self.xedge[-1]\n ymin = self.yedge[-1]\n ymax = self.yedge[0]\n lines = []\n # Vertical lines\n for j in range(self.ncol + 1):\n x0 = self.xedge[j]\n x1 = x0\n y0 = ymin\n y1 = ymax\n x0r, y0r = self.transform(x0, y0)\n x1r, y1r = self.transform(x1, y1)\n lines.append([(x0r, y0r), (x1r, y1r)])\n\n # horizontal lines\n for i in range(self.nrow + 1):\n x0 = xmin\n x1 = xmax\n y0 = self.yedge[i]\n y1 = y0\n x0r, y0r = self.transform(x0, y0)\n x1r, y1r = self.transform(x1, y1)\n lines.append([(x0r, y0r), (x1r, y1r)])\n return lines\n\n def get_grid_line_collection(self, **kwargs):\n \"\"\"\n Get a LineCollection of the grid\n\n \"\"\"\n from ..plot import ModelMap\n\n map = ModelMap(sr=self)\n lc = map.plot_grid(**kwargs)\n return lc\n\n def get_xcenter_array(self):\n \"\"\"\n Return a numpy one-dimensional float array that has the cell center x\n coordinate for every column in the grid in model space - not offset or rotated.\n\n \"\"\"\n x = np.add.accumulate(self.delr) - 0.5 * self.delr\n return x\n\n def get_ycenter_array(self):\n \"\"\"\n Return a numpy one-dimensional float array that has the cell center x\n coordinate for every row in the grid in model space - not offset of rotated.\n\n \"\"\"\n Ly = np.add.reduce(self.delc)\n y = Ly - (np.add.accumulate(self.delc) - 0.5 * self.delc)\n return y\n\n def get_xedge_array(self):\n \"\"\"\n Return a numpy one-dimensional float array that has the cell edge x\n coordinates for every column in the grid in model space - not offset\n or rotated. Array is of size (ncol + 1)\n\n \"\"\"\n xedge = np.concatenate(([0.0], np.add.accumulate(self.delr)))\n return xedge\n\n def get_yedge_array(self):\n \"\"\"\n Return a numpy one-dimensional float array that has the cell edge y\n coordinates for every row in the grid in model space - not offset or\n rotated. Array is of size (nrow + 1)\n\n \"\"\"\n length_y = np.add.reduce(self.delc)\n yedge = np.concatenate(\n ([length_y], length_y - np.add.accumulate(self.delc))\n )\n return yedge\n\n def write_gridSpec(self, filename):\n \"\"\"write a PEST-style grid specification file\"\"\"\n f = open(filename, \"w\")\n f.write(\n \"{0:10d} {1:10d}\\n\".format(self.delc.shape[0], self.delr.shape[0])\n )\n f.write(\n \"{0:15.6E} {1:15.6E} {2:15.6E}\\n\".format(\n self.xul * self.length_multiplier,\n self.yul * self.length_multiplier,\n self.rotation,\n )\n )\n\n for r in self.delr:\n f.write(\"{0:15.6E} \".format(r))\n f.write(\"\\n\")\n for c in self.delc:\n f.write(\"{0:15.6E} \".format(c))\n f.write(\"\\n\")\n return\n\n def write_shapefile(self, filename=\"grid.shp\", epsg=None, prj=None):\n \"\"\"Write a shapefile of the grid with just the row and column attributes\"\"\"\n from ..export.shapefile_utils import write_grid_shapefile\n\n if epsg is None and prj is None:\n epsg = self.epsg\n write_grid_shapefile(\n filename, self, array_dict={}, nan_val=-1.0e9, epsg=epsg, prj=prj\n )\n\n def get_vertices(self, i, j):\n \"\"\"Get vertices for a single cell or sequence if i, j locations.\"\"\"\n pts = []\n xgrid, ygrid = self.xgrid, self.ygrid\n pts.append([xgrid[i, j], ygrid[i, j]])\n pts.append([xgrid[i + 1, j], ygrid[i + 1, j]])\n pts.append([xgrid[i + 1, j + 1], ygrid[i + 1, j + 1]])\n pts.append([xgrid[i, j + 1], ygrid[i, j + 1]])\n pts.append([xgrid[i, j], ygrid[i, j]])\n if np.isscalar(i):\n return pts\n else:\n vrts = np.array(pts).transpose([2, 0, 1])\n return [v.tolist() for v in vrts]\n\n def get_rc(self, x, y):\n return self.get_ij(x, y)\n\n def get_ij(self, x, y):\n \"\"\"Return the row and column of a point or sequence of points\n in real-world coordinates.\n\n Parameters\n ----------\n x : scalar or sequence of x coordinates\n y : scalar or sequence of y coordinates\n\n Returns\n -------\n i : row or sequence of rows (zero-based)\n j : column or sequence of columns (zero-based)\n \"\"\"\n if np.isscalar(x):\n c = (np.abs(self.xcentergrid[0] - x)).argmin()\n r = (np.abs(self.ycentergrid[:, 0] - y)).argmin()\n else:\n xcp = np.array([self.xcentergrid[0]] * (len(x)))\n ycp = np.array([self.ycentergrid[:, 0]] * (len(x)))\n c = (np.abs(xcp.transpose() - x)).argmin(axis=0)\n r = (np.abs(ycp.transpose() - y)).argmin(axis=0)\n return r, c\n\n def get_grid_map_plotter(self, **kwargs):\n \"\"\"\n Create a QuadMesh plotting object for this grid\n\n Returns\n -------\n quadmesh : matplotlib.collections.QuadMesh\n\n \"\"\"\n try:\n from matplotlib.collections import QuadMesh\n except:\n err_msg = (\n \"matplotlib must be installed to \"\n + \"use get_grid_map_plotter()\"\n )\n raise ImportError(err_msg)\n\n verts = np.vstack((self.xgrid.flatten(), self.ygrid.flatten())).T\n qm = QuadMesh(self.ncol, self.nrow, verts)\n return qm\n\n def plot_array(self, a, ax=None, **kwargs):\n \"\"\"\n Create a QuadMesh plot of the specified array using pcolormesh\n\n Parameters\n ----------\n a : np.ndarray\n\n Returns\n -------\n quadmesh : matplotlib.collections.QuadMesh\n\n \"\"\"\n try:\n import matplotlib.pyplot as plt\n except:\n err_msg = (\n \"matplotlib must be installed to \"\n + \"use reference.plot_array()\"\n )\n raise ImportError(err_msg)\n\n if ax is None:\n ax = plt.gca()\n qm = ax.pcolormesh(self.xgrid, self.ygrid, a, **kwargs)\n return qm\n\n def export_array(\n self, filename, a, nodata=-9999, fieldname=\"value\", **kwargs\n ):\n \"\"\"\n Write a numpy array to Arc Ascii grid or shapefile with the\n model reference.\n\n Parameters\n ----------\n filename : str\n Path of output file. Export format is determined by\n file extension.\n '.asc' Arc Ascii grid\n '.tif' GeoTIFF (requires rasterio package)\n '.shp' Shapefile\n a : 2D numpy.ndarray\n Array to export\n nodata : scalar\n Value to assign to np.nan entries (default -9999)\n fieldname : str\n Attribute field name for array values (shapefile export only).\n (default 'values')\n kwargs:\n keyword arguments to np.savetxt (ascii)\n rasterio.open (GeoTIFF)\n or flopy.export.shapefile_utils.write_grid_shapefile2\n\n Notes\n -----\n Rotated grids will be either be unrotated prior to export,\n using scipy.ndimage.rotate (Arc Ascii format) or rotation will be\n included in their transform property (GeoTiff format). In either case\n the pixels will be displayed in the (unrotated) projected geographic coordinate system,\n so the pixels will no longer align exactly with the model grid\n (as displayed from a shapefile, for example). A key difference between\n Arc Ascii and GeoTiff (besides disk usage) is that the\n unrotated Arc Ascii will have a different grid size, whereas the GeoTiff\n will have the same number of rows and pixels as the original.\n\n \"\"\"\n\n if filename.lower().endswith(\".asc\"):\n if (\n len(np.unique(self.delr)) != len(np.unique(self.delc)) != 1\n or self.delr[0] != self.delc[0]\n ):\n raise ValueError(\"Arc ascii arrays require a uniform grid.\")\n\n xll, yll = self.xll, self.yll\n cellsize = self.delr[0] * self.length_multiplier\n fmt = kwargs.get(\"fmt\", \"%.18e\")\n a = a.copy()\n a[np.isnan(a)] = nodata\n if self.rotation != 0:\n try:\n from scipy.ndimage import rotate\n\n a = rotate(a, self.rotation, cval=nodata)\n height_rot, width_rot = a.shape\n xmin, ymin, xmax, ymax = self.bounds\n dx = (xmax - xmin) / width_rot\n dy = (ymax - ymin) / height_rot\n cellsize = np.max((dx, dy))\n # cellsize = np.cos(np.radians(self.rotation)) * cellsize\n xll, yll = xmin, ymin\n except ImportError:\n print(\"scipy package required to export rotated grid.\")\n\n filename = (\n \".\".join(filename.split(\".\")[:-1]) + \".asc\"\n ) # enforce .asc ending\n nrow, ncol = a.shape\n a[np.isnan(a)] = nodata\n txt = \"ncols {:d}\\n\".format(ncol)\n txt += \"nrows {:d}\\n\".format(nrow)\n txt += \"xllcorner {:f}\\n\".format(xll)\n txt += \"yllcorner {:f}\\n\".format(yll)\n txt += \"cellsize {}\\n\".format(cellsize)\n # ensure that nodata fmt consistent w values\n txt += \"NODATA_value {}\\n\".format(fmt) % (nodata)\n with open(filename, \"w\") as output:\n output.write(txt)\n with open(filename, \"ab\") as output:\n np.savetxt(output, a, **kwargs)\n print(\"wrote {}\".format(filename))\n\n elif filename.lower().endswith(\".tif\"):\n if (\n len(np.unique(self.delr)) != len(np.unique(self.delc)) != 1\n or self.delr[0] != self.delc[0]\n ):\n raise ValueError(\"GeoTIFF export require a uniform grid.\")\n try:\n import rasterio\n from rasterio import Affine\n except:\n print(\"GeoTIFF export requires the rasterio package.\")\n return\n dxdy = self.delc[0] * self.length_multiplier\n trans = (\n Affine.translation(self.xul, self.yul)\n * Affine.rotation(self.rotation)\n * Affine.scale(dxdy, -dxdy)\n )\n\n # third dimension is the number of bands\n a = a.copy()\n if len(a.shape) == 2:\n a = np.reshape(a, (1, a.shape[0], a.shape[1]))\n if a.dtype.name == \"int64\":\n a = a.astype(\"int32\")\n dtype = rasterio.int32\n elif a.dtype.name == \"int32\":\n dtype = rasterio.int32\n elif a.dtype.name == \"float64\":\n dtype = rasterio.float64\n elif a.dtype.name == \"float32\":\n dtype = rasterio.float32\n else:\n msg = 'ERROR: invalid dtype \"{}\"'.format(a.dtype.name)\n raise TypeError(msg)\n\n meta = {\n \"count\": a.shape[0],\n \"width\": a.shape[2],\n \"height\": a.shape[1],\n \"nodata\": nodata,\n \"dtype\": dtype,\n \"driver\": \"GTiff\",\n \"crs\": self.proj4_str,\n \"transform\": trans,\n }\n meta.update(kwargs)\n with rasterio.open(filename, \"w\", **meta) as dst:\n dst.write(a)\n print(\"wrote {}\".format(filename))\n\n elif filename.lower().endswith(\".shp\"):\n from ..export.shapefile_utils import write_grid_shapefile\n\n epsg = kwargs.get(\"epsg\", None)\n prj = kwargs.get(\"prj\", None)\n if epsg is None and prj is None:\n epsg = self.epsg\n write_grid_shapefile(\n filename,\n self,\n array_dict={fieldname: a},\n nan_val=nodata,\n epsg=epsg,\n prj=prj,\n )\n\n def export_contours(\n self,\n filename,\n contours,\n fieldname=\"level\",\n epsg=None,\n prj=None,\n **kwargs\n ):\n \"\"\"\n Convert matplotlib contour plot object to shapefile.\n\n Parameters\n ----------\n filename : str\n path of output shapefile\n contours : matplotlib.contour.QuadContourSet or list of them\n (object returned by matplotlib.pyplot.contour)\n epsg : int\n EPSG code. See https://www.epsg-registry.org/ or spatialreference.org\n prj : str\n Existing projection file to be used with new shapefile.\n **kwargs : key-word arguments to flopy.export.shapefile_utils.recarray2shp\n\n Returns\n -------\n df : dataframe of shapefile contents\n\n \"\"\"\n from flopy.utils.geometry import LineString\n from flopy.export.shapefile_utils import recarray2shp\n\n if not isinstance(contours, list):\n contours = [contours]\n\n if epsg is None:\n epsg = self._epsg\n if prj is None:\n prj = self.proj4_str\n\n geoms = []\n level = []\n for ctr in contours:\n levels = ctr.levels\n for i, c in enumerate(ctr.collections):\n paths = c.get_paths()\n geoms += [LineString(p.vertices) for p in paths]\n level += list(np.ones(len(paths)) * levels[i])\n\n # convert the dictionary to a recarray\n ra = np.array(level, dtype=[(fieldname, float)]).view(np.recarray)\n\n recarray2shp(ra, geoms, filename, epsg=epsg, prj=prj, **kwargs)\n\n def export_array_contours(\n self,\n filename,\n a,\n fieldname=\"level\",\n interval=None,\n levels=None,\n maxlevels=1000,\n epsg=None,\n prj=None,\n **kwargs\n ):\n \"\"\"\n Contour an array using matplotlib; write shapefile of contours.\n\n Parameters\n ----------\n filename : str\n Path of output file with '.shp' extension.\n a : 2D numpy array\n Array to contour\n epsg : int\n EPSG code. See https://www.epsg-registry.org/ or spatialreference.org\n prj : str\n Existing projection file to be used with new shapefile.\n **kwargs : key-word arguments to flopy.export.shapefile_utils.recarray2shp\n\n \"\"\"\n try:\n import matplotlib.pyplot as plt\n except:\n err_msg = (\n \"matplotlib must be installed to \"\n + \"use cvfd_to_patch_collection()\"\n )\n raise ImportError(err_msg)\n\n if epsg is None:\n epsg = self._epsg\n if prj is None:\n prj = self.proj4_str\n\n if interval is not None:\n vmin = np.nanmin(a)\n vmax = np.nanmax(a)\n nlevels = np.round(np.abs(vmax - vmin) / interval, 2)\n msg = (\n \"{:.0f} levels \".format(nlevels)\n + \"at interval of {} > \".format(interval)\n + \"maxlevels = {}\".format(maxlevels)\n )\n assert nlevels < maxlevels, msg\n levels = np.arange(vmin, vmax, interval)\n fig, ax = plt.subplots()\n ctr = self.contour_array(ax, a, levels=levels)\n self.export_contours(filename, ctr, fieldname, epsg, prj, **kwargs)\n plt.close()\n\n def contour_array(self, ax, a, **kwargs):\n \"\"\"\n Create a QuadMesh plot of the specified array using pcolormesh\n\n Parameters\n ----------\n ax : matplotlib.axes.Axes\n ax to add the contours\n\n a : np.ndarray\n array to contour\n\n Returns\n -------\n contour_set : ContourSet\n\n \"\"\"\n from flopy.plot import ModelMap\n\n kwargs[\"ax\"] = ax\n mm = ModelMap(sr=self)\n contour_set = mm.contour_array(a=a, **kwargs)\n\n return contour_set\n\n @property\n def vertices(self):\n \"\"\"\n Returns a list of vertices for\n \"\"\"\n if self._vertices is None:\n self._set_vertices()\n return self._vertices\n\n def _set_vertices(self):\n \"\"\"\n Populate vertices for the whole grid\n \"\"\"\n jj, ii = np.meshgrid(range(self.ncol), range(self.nrow))\n jj, ii = jj.ravel(), ii.ravel()\n self._vertices = self.get_vertices(ii, jj)\n\n def interpolate(self, a, xi, method=\"nearest\"):\n \"\"\"\n Use the griddata method to interpolate values from an array onto the\n points defined in xi. For any values outside of the grid, use\n 'nearest' to find a value for them.\n\n Parameters\n ----------\n a : numpy.ndarray\n array to interpolate from. It must be of size nrow, ncol\n xi : numpy.ndarray\n array containing x and y point coordinates of size (npts, 2). xi\n also works with broadcasting so that if a is a 2d array, then\n xi can be passed in as (xgrid, ygrid).\n method : {'linear', 'nearest', 'cubic'}\n method to use for interpolation (default is 'nearest')\n\n Returns\n -------\n b : numpy.ndarray\n array of size (npts)\n\n \"\"\"\n try:\n from scipy.interpolate import griddata\n except:\n print(\"scipy not installed\\ntry pip install scipy\")\n return None\n\n # Create a 2d array of points for the grid centers\n points = np.empty((self.ncol * self.nrow, 2))\n points[:, 0] = self.xcentergrid.flatten()\n points[:, 1] = self.ycentergrid.flatten()\n\n # Use the griddata function to interpolate to the xi points\n b = griddata(points, a.flatten(), xi, method=method, fill_value=np.nan)\n\n # if method is linear or cubic, then replace nan's with a value\n # interpolated using nearest\n if method != \"nearest\":\n bn = griddata(points, a.flatten(), xi, method=\"nearest\")\n idx = np.isnan(b)\n b[idx] = bn[idx]\n\n return b\n\n def get_2d_vertex_connectivity(self):\n \"\"\"\n Create the cell 2d vertices array and the iverts index array. These\n are the same form as the ones used to instantiate an unstructured\n spatial reference.\n\n Returns\n -------\n\n verts : ndarray\n array of x and y coordinates for the grid vertices\n\n iverts : list\n a list with a list of vertex indices for each cell in clockwise\n order starting with the upper left corner\n\n \"\"\"\n x = self.xgrid.flatten()\n y = self.ygrid.flatten()\n nrowvert = self.nrow + 1\n ncolvert = self.ncol + 1\n npoints = nrowvert * ncolvert\n verts = np.empty((npoints, 2), dtype=float)\n verts[:, 0] = x\n verts[:, 1] = y\n iverts = []\n for i in range(self.nrow):\n for j in range(self.ncol):\n iv1 = i * ncolvert + j # upper left point number\n iv2 = iv1 + 1\n iv4 = (i + 1) * ncolvert + j\n iv3 = iv4 + 1\n iverts.append([iv1, iv2, iv3, iv4])\n return verts, iverts\n\n def get_3d_shared_vertex_connectivity(self, nlay, botm, ibound=None):\n\n # get the x and y points for the grid\n x = self.xgrid.flatten()\n y = self.ygrid.flatten()\n\n # set the size of the vertex grid\n nrowvert = self.nrow + 1\n ncolvert = self.ncol + 1\n nlayvert = nlay + 1\n nrvncv = nrowvert * ncolvert\n npoints = nrvncv * nlayvert\n\n # create and fill a 3d points array for the grid\n verts = np.empty((npoints, 3), dtype=float)\n verts[:, 0] = np.tile(x, nlayvert)\n verts[:, 1] = np.tile(y, nlayvert)\n istart = 0\n istop = nrvncv\n for k in range(nlay + 1):\n verts[istart:istop, 2] = self.interpolate(\n botm[k], verts[istart:istop, :2], method=\"linear\"\n )\n istart = istop\n istop = istart + nrvncv\n\n # create the list of points comprising each cell. points must be\n # listed a specific way according to vtk requirements.\n iverts = []\n for k in range(nlay):\n koffset = k * nrvncv\n for i in range(self.nrow):\n for j in range(self.ncol):\n if ibound is not None:\n if ibound[k, i, j] == 0:\n continue\n iv1 = i * ncolvert + j + koffset\n iv2 = iv1 + 1\n iv4 = (i + 1) * ncolvert + j + koffset\n iv3 = iv4 + 1\n iverts.append(\n [\n iv4 + nrvncv,\n iv3 + nrvncv,\n iv1 + nrvncv,\n iv2 + nrvncv,\n iv4,\n iv3,\n iv1,\n iv2,\n ]\n )\n\n # renumber and reduce the vertices if ibound_filter\n if ibound is not None:\n\n # go through the vertex list and mark vertices that are used\n ivertrenum = np.zeros(npoints, dtype=int)\n for vlist in iverts:\n for iv in vlist:\n # mark vertices that are actually used\n ivertrenum[iv] = 1\n\n # renumber vertices that are used, skip those that are not\n inum = 0\n for i in range(npoints):\n if ivertrenum[i] > 0:\n inum += 1\n ivertrenum[i] = inum\n ivertrenum -= 1\n\n # reassign the vertex list using the new vertex numbers\n iverts2 = []\n for vlist in iverts:\n vlist2 = []\n for iv in vlist:\n vlist2.append(ivertrenum[iv])\n iverts2.append(vlist2)\n iverts = iverts2\n idx = np.where(ivertrenum >= 0)\n verts = verts[idx]\n\n return verts, iverts\n\n def get_3d_vertex_connectivity(self, nlay, top, bot, ibound=None):\n if ibound is None:\n ncells = nlay * self.nrow * self.ncol\n ibound = np.ones((nlay, self.nrow, self.ncol), dtype=int)\n else:\n ncells = (ibound != 0).sum()\n npoints = ncells * 8\n verts = np.empty((npoints, 3), dtype=float)\n iverts = []\n ipoint = 0\n for k in range(nlay):\n for i in range(self.nrow):\n for j in range(self.ncol):\n if ibound[k, i, j] == 0:\n continue\n\n ivert = []\n pts = self.get_vertices(i, j)\n pt0, pt1, pt2, pt3, pt0 = pts\n\n z = bot[k, i, j]\n\n verts[ipoint, 0:2] = np.array(pt1)\n verts[ipoint, 2] = z\n ivert.append(ipoint)\n ipoint += 1\n\n verts[ipoint, 0:2] = np.array(pt2)\n verts[ipoint, 2] = z\n ivert.append(ipoint)\n ipoint += 1\n\n verts[ipoint, 0:2] = np.array(pt0)\n verts[ipoint, 2] = z\n ivert.append(ipoint)\n ipoint += 1\n\n verts[ipoint, 0:2] = np.array(pt3)\n verts[ipoint, 2] = z\n ivert.append(ipoint)\n ipoint += 1\n\n z = top[k, i, j]\n\n verts[ipoint, 0:2] = np.array(pt1)\n verts[ipoint, 2] = z\n ivert.append(ipoint)\n ipoint += 1\n\n verts[ipoint, 0:2] = np.array(pt2)\n verts[ipoint, 2] = z\n ivert.append(ipoint)\n ipoint += 1\n\n verts[ipoint, 0:2] = np.array(pt0)\n verts[ipoint, 2] = z\n ivert.append(ipoint)\n ipoint += 1\n\n verts[ipoint, 0:2] = np.array(pt3)\n verts[ipoint, 2] = z\n ivert.append(ipoint)\n ipoint += 1\n\n iverts.append(ivert)\n\n return verts, iverts\n\n\nclass SpatialReferenceUnstructured(SpatialReference):\n \"\"\"\n a class to locate an unstructured model grid in x-y space\n\n .. deprecated:: 3.2.11\n This class will be removed in version 3.3.5. Use\n :py:class:`flopy.discretization.vertexgrid.VertexGrid` instead.\n\n Parameters\n ----------\n\n verts : ndarray\n 2d array of x and y points.\n\n iverts : list of lists\n should be of len(ncells) with a list of vertex numbers for each cell\n\n ncpl : ndarray\n array containing the number of cells per layer. ncpl.sum() must be\n equal to the total number of cells in the grid.\n\n layered : boolean\n flag to indicated that the grid is layered. In this case, the vertices\n define the grid for single layer, and all layers use this same grid.\n In this case the ncpl value for each layer must equal len(iverts).\n If not layered, then verts and iverts are specified for all cells and\n all layers in the grid. In this case, npcl.sum() must equal\n len(iverts).\n\n lenuni : int\n the length units flag from the discretization package\n\n proj4_str: str\n a PROJ4 string that identifies the grid in space. warning: case\n sensitive!\n\n units : string\n Units for the grid. Must be either feet or meters\n\n epsg : int\n EPSG code that identifies the grid in space. Can be used in lieu of\n proj4. PROJ4 attribute will auto-populate if there is an internet\n connection(via get_proj4 method).\n See https://www.epsg-registry.org/ or spatialreference.org\n\n length_multiplier : float\n multiplier to convert model units to spatial reference units.\n delr and delc above will be multiplied by this value. (default=1.)\n\n Attributes\n ----------\n xcenter : ndarray\n array of x cell centers\n\n ycenter : ndarray\n array of y cell centers\n\n Notes\n -----\n\n \"\"\"\n\n def __init__(\n self,\n xc,\n yc,\n verts,\n iverts,\n ncpl,\n layered=True,\n lenuni=1,\n proj4_str=None,\n epsg=None,\n units=None,\n length_multiplier=1.0,\n ):\n warnings.warn(\n \"SpatialReferenceUnstructured has been deprecated and will be \"\n \"removed in version 3.3.5. Use VertexGrid instead.\",\n category=DeprecationWarning,\n )\n self.xc = xc\n self.yc = yc\n self.verts = verts\n self.iverts = iverts\n self.ncpl = ncpl\n self.layered = layered\n self._lenuni = lenuni\n self._proj4_str = proj4_str\n self._epsg = epsg\n if epsg is not None:\n self._proj4_str = getproj4(epsg)\n self.supported_units = [\"feet\", \"meters\"]\n self._units = units\n self._length_multiplier = length_multiplier\n\n # set defaults\n self._xul = 0.0\n self._yul = 0.0\n self.rotation = 0.0\n\n if self.layered:\n assert all([n == len(iverts) for n in ncpl])\n assert self.xc.shape[0] == self.ncpl[0]\n assert self.yc.shape[0] == self.ncpl[0]\n else:\n msg = \"Length of iverts must equal ncpl.sum \" \"({} {})\".format(\n len(iverts), ncpl\n )\n assert len(iverts) == ncpl.sum(), msg\n assert self.xc.shape[0] == self.ncpl.sum()\n assert self.yc.shape[0] == self.ncpl.sum()\n return\n\n @property\n def grid_type(self):\n return \"unstructured\"\n\n def write_shapefile(self, filename=\"grid.shp\"):\n \"\"\"\n Write shapefile of the grid\n\n Parameters\n ----------\n filename : string\n filename for shapefile\n\n Returns\n -------\n\n \"\"\"\n raise NotImplementedError()\n return\n\n def write_gridSpec(self, filename):\n \"\"\"\n Write a PEST-style grid specification file\n\n Parameters\n ----------\n filename : string\n filename for grid specification file\n\n Returns\n -------\n\n \"\"\"\n raise NotImplementedError()\n return\n\n @classmethod\n def from_gridspec(cls, fname):\n \"\"\"\n Create a new SpatialReferenceUnstructured grid from an PEST\n grid specification file\n\n Parameters\n ----------\n fname : string\n File name for grid specification file\n\n Returns\n -------\n sru : flopy.utils.reference.SpatialReferenceUnstructured\n\n \"\"\"\n raise NotImplementedError()\n return\n\n @classmethod\n def from_argus_export(cls, fname, nlay=1):\n \"\"\"\n Create a new SpatialReferenceUnstructured grid from an Argus One\n Trimesh file\n\n Parameters\n ----------\n fname : string\n File name\n\n nlay : int\n Number of layers to create\n\n Returns\n -------\n sru : flopy.utils.reference.SpatialReferenceUnstructured\n\n \"\"\"\n from ..utils.geometry import get_polygon_centroid\n\n f = open(fname, \"r\")\n line = f.readline()\n ll = line.split()\n ncells, nverts = ll[0:2]\n ncells = int(ncells)\n nverts = int(nverts)\n verts = np.empty((nverts, 2), dtype=float)\n xc = np.empty((ncells), dtype=float)\n yc = np.empty((ncells), dtype=float)\n\n # read the vertices\n f.readline()\n for ivert in range(nverts):\n line = f.readline()\n ll = line.split()\n c, iv, x, y = ll[0:4]\n verts[ivert, 0] = x\n verts[ivert, 1] = y\n\n # read the cell information and create iverts, xc, and yc\n iverts = []\n for icell in range(ncells):\n line = f.readline()\n ll = line.split()\n ivlist = []\n for ic in ll[2:5]:\n ivlist.append(int(ic) - 1)\n if ivlist[0] != ivlist[-1]:\n ivlist.append(ivlist[0])\n iverts.append(ivlist)\n xc[icell], yc[icell] = get_polygon_centroid(verts[ivlist, :])\n\n # close file and return spatial reference\n f.close()\n return cls(xc, yc, verts, iverts, np.array(nlay * [len(iverts)]))\n\n def __setattr__(self, key, value):\n super(SpatialReference, self).__setattr__(key, value)\n return\n\n def get_extent(self):\n \"\"\"\n Get the extent of the grid\n\n Returns\n -------\n extent : tuple\n min and max grid coordinates\n\n \"\"\"\n xmin = self.verts[:, 0].min()\n xmax = self.verts[:, 0].max()\n ymin = self.verts[:, 1].min()\n ymax = self.verts[:, 1].max()\n return (xmin, xmax, ymin, ymax)\n\n def get_xcenter_array(self):\n \"\"\"\n Return a numpy one-dimensional float array that has the cell center x\n coordinate for every cell in the grid in model space - not offset or\n rotated.\n\n \"\"\"\n return self.xc\n\n def get_ycenter_array(self):\n \"\"\"\n Return a numpy one-dimensional float array that has the cell center x\n coordinate for every cell in the grid in model space - not offset of\n rotated.\n\n \"\"\"\n return self.yc\n\n def plot_array(self, a, ax=None):\n \"\"\"\n Create a QuadMesh plot of the specified array using patches\n\n Parameters\n ----------\n a : np.ndarray\n\n Returns\n -------\n pc : matplotlib.collections.PatchCollection\n\n \"\"\"\n from ..plot import ModelMap\n\n pmv = ModelMap(sr=self, ax=ax)\n pc = pmv.plot_array(a)\n\n return pc\n\n def get_grid_line_collection(self, **kwargs):\n \"\"\"\n Get a patch collection of the grid\n\n \"\"\"\n from ..plot import ModelMap\n\n ax = kwargs.pop(\"ax\", None)\n pmv = ModelMap(sr=self, ax=ax)\n pc = pmv.plot_grid(**kwargs)\n return pc\n\n def contour_array(self, ax, a, **kwargs):\n \"\"\"\n Create a QuadMesh plot of the specified array using pcolormesh\n\n Parameters\n ----------\n ax : matplotlib.axes.Axes\n ax to add the contours\n\n a : np.ndarray\n array to contour\n\n Returns\n -------\n contour_set : ContourSet\n\n \"\"\"\n contour_set = ax.tricontour(self.xcenter, self.ycenter, a, **kwargs)\n return contour_set\n\n\nclass TemporalReference:\n \"\"\"\n For now, just a container to hold start time and time units files\n outside of DIS package.\n \"\"\"\n\n defaults = {\"itmuni\": 4, \"start_datetime\": \"01-01-1970\"}\n\n itmuni_values = {\n \"undefined\": 0,\n \"seconds\": 1,\n \"minutes\": 2,\n \"hours\": 3,\n \"days\": 4,\n \"years\": 5,\n }\n\n itmuni_text = {v: k for k, v in itmuni_values.items()}\n\n def __init__(self, itmuni=4, start_datetime=None):\n self.itmuni = itmuni\n self.start_datetime = start_datetime\n\n @property\n def model_time_units(self):\n return self.itmuni_text[self.itmuni]\n\n\nclass epsgRef:\n \"\"\"\n Sets up a local database of text representations of coordinate reference\n systems, keyed by EPSG code.\n\n The database is epsgref.json, located in the user's data directory. If\n optional 'appdirs' package is available, this is in the platform-dependent\n user directory, otherwise in the user's 'HOME/.flopy' directory.\n\n .. deprecated:: 3.2.11\n This class will be removed in version 3.3.5.\n \"\"\"\n\n def __init__(self):\n warnings.warn(\n \"epsgRef has been deprecated and will be removed in version \"\n \"3.3.5.\",\n category=DeprecationWarning,\n )\n try:\n from appdirs import user_data_dir\n except ImportError:\n user_data_dir = None\n if user_data_dir:\n datadir = user_data_dir(\"flopy\")\n else:\n # if appdirs is not installed, use user's home directory\n datadir = os.path.join(os.path.expanduser(\"~\"), \".flopy\")\n if not os.path.isdir(datadir):\n os.makedirs(datadir)\n dbname = \"epsgref.json\"\n self.location = os.path.join(datadir, dbname)\n\n def to_dict(self):\n \"\"\"\n Returns dict with EPSG code integer key, and WKT CRS text\n \"\"\"\n data = OrderedDict()\n if os.path.exists(self.location):\n with open(self.location, \"r\") as f:\n loaded_data = json.load(f, object_pairs_hook=OrderedDict)\n # convert JSON key from str to EPSG integer\n for key, value in loaded_data.items():\n try:\n data[int(key)] = value\n except ValueError:\n data[key] = value\n return data\n\n def _write(self, data):\n with open(self.location, \"w\") as f:\n json.dump(data, f, indent=0)\n f.write(\"\\n\")\n\n def reset(self, verbose=True):\n if os.path.exists(self.location):\n os.remove(self.location)\n if verbose:\n print(\"Resetting {}\".format(self.location))\n\n def add(self, epsg, prj):\n \"\"\"\n add an epsg code to epsgref.json\n \"\"\"\n data = self.to_dict()\n data[epsg] = prj\n self._write(data)\n\n def get(self, epsg):\n \"\"\"\n returns prj from a epsg code, otherwise None if not found\n \"\"\"\n data = self.to_dict()\n return data.get(epsg)\n\n def remove(self, epsg):\n \"\"\"\n removes an epsg entry from epsgref.json\n \"\"\"\n data = self.to_dict()\n if epsg in data:\n del data[epsg]\n self._write(data)\n\n @staticmethod\n def show():\n ep = epsgRef()\n prj = ep.to_dict()\n for k, v in prj.items():\n print(\"{}:\\n{}\\n\".format(k, v))\n\n\nclass crs:\n \"\"\"\n Container to parse and store coordinate reference system parameters,\n and translate between different formats.\n\n .. deprecated:: 3.2.11\n This class will be removed in version 3.3.5. Use\n :py:class:`flopy.export.shapefile_utils.CRS` instead.\n \"\"\"\n\n def __init__(self, prj=None, esri_wkt=None, epsg=None):\n warnings.warn(\n \"crs has been deprecated and will be removed in version 3.3.5. \"\n \"Use CRS in shapefile_utils instead.\",\n category=DeprecationWarning,\n )\n self.wktstr = None\n if prj is not None:\n with open(prj) as fprj:\n self.wktstr = fprj.read()\n elif esri_wkt is not None:\n self.wktstr = esri_wkt\n elif epsg is not None:\n wktstr = getprj(epsg)\n if wktstr is not None:\n self.wktstr = wktstr\n if self.wktstr is not None:\n self.parse_wkt()\n\n @property\n def crs(self):\n \"\"\"\n Dict mapping crs attributes to proj4 parameters\n \"\"\"\n proj = None\n if self.projcs is not None:\n # projection\n if \"mercator\" in self.projcs.lower():\n if (\n \"transverse\" in self.projcs.lower()\n or \"tm\" in self.projcs.lower()\n ):\n proj = \"tmerc\"\n else:\n proj = \"merc\"\n elif (\n \"utm\" in self.projcs.lower() and \"zone\" in self.projcs.lower()\n ):\n proj = \"utm\"\n elif \"stateplane\" in self.projcs.lower():\n proj = \"lcc\"\n elif \"lambert\" and \"conformal\" and \"conic\" in self.projcs.lower():\n proj = \"lcc\"\n elif \"albers\" in self.projcs.lower():\n proj = \"aea\"\n elif self.projcs is None and self.geogcs is not None:\n proj = \"longlat\"\n\n # datum\n datum = None\n if (\n \"NAD\" in self.datum.lower()\n or \"north\" in self.datum.lower()\n and \"america\" in self.datum.lower()\n ):\n datum = \"nad\"\n if \"83\" in self.datum.lower():\n datum += \"83\"\n elif \"27\" in self.datum.lower():\n datum += \"27\"\n elif \"84\" in self.datum.lower():\n datum = \"wgs84\"\n\n # ellipse\n ellps = None\n if \"1866\" in self.spheroid_name:\n ellps = \"clrk66\"\n elif \"grs\" in self.spheroid_name.lower():\n ellps = \"grs80\"\n elif \"wgs\" in self.spheroid_name.lower():\n ellps = \"wgs84\"\n\n # prime meridian\n pm = self.primem[0].lower()\n\n return {\n \"proj\": proj,\n \"datum\": datum,\n \"ellps\": ellps,\n \"a\": self.semi_major_axis,\n \"rf\": self.inverse_flattening,\n \"lat_0\": self.latitude_of_origin,\n \"lat_1\": self.standard_parallel_1,\n \"lat_2\": self.standard_parallel_2,\n \"lon_0\": self.central_meridian,\n \"k_0\": self.scale_factor,\n \"x_0\": self.false_easting,\n \"y_0\": self.false_northing,\n \"units\": self.projcs_unit,\n \"zone\": self.utm_zone,\n }\n\n @property\n def grid_mapping_attribs(self):\n \"\"\"\n Map parameters for CF Grid Mappings\n http://http://cfconventions.org/cf-conventions/cf-conventions.html,\n Appendix F: Grid Mappings\n \"\"\"\n if self.wktstr is not None:\n sp = [\n p\n for p in [self.standard_parallel_1, self.standard_parallel_2]\n if p is not None\n ]\n sp = sp if len(sp) > 0 else None\n proj = self.crs[\"proj\"]\n names = {\n \"aea\": \"albers_conical_equal_area\",\n \"aeqd\": \"azimuthal_equidistant\",\n \"laea\": \"lambert_azimuthal_equal_area\",\n \"longlat\": \"latitude_longitude\",\n \"lcc\": \"lambert_conformal_conic\",\n \"merc\": \"mercator\",\n \"tmerc\": \"transverse_mercator\",\n \"utm\": \"transverse_mercator\",\n }\n attribs = {\n \"grid_mapping_name\": names[proj],\n \"semi_major_axis\": self.crs[\"a\"],\n \"inverse_flattening\": self.crs[\"rf\"],\n \"standard_parallel\": sp,\n \"longitude_of_central_meridian\": self.crs[\"lon_0\"],\n \"latitude_of_projection_origin\": self.crs[\"lat_0\"],\n \"scale_factor_at_projection_origin\": self.crs[\"k_0\"],\n \"false_easting\": self.crs[\"x_0\"],\n \"false_northing\": self.crs[\"y_0\"],\n }\n return {k: v for k, v in attribs.items() if v is not None}\n\n @property\n def proj4(self):\n \"\"\"\n Not implemented yet\n \"\"\"\n return None\n\n def parse_wkt(self):\n\n self.projcs = self._gettxt('PROJCS[\"', '\"')\n self.utm_zone = None\n if self.projcs is not None and \"utm\" in self.projcs.lower():\n self.utm_zone = self.projcs[-3:].lower().strip(\"n\").strip(\"s\")\n self.geogcs = self._gettxt('GEOGCS[\"', '\"')\n self.datum = self._gettxt('DATUM[\"', '\"')\n tmp = self._getgcsparam(\"SPHEROID\")\n self.spheroid_name = tmp.pop(0)\n self.semi_major_axis = tmp.pop(0)\n self.inverse_flattening = tmp.pop(0)\n self.primem = self._getgcsparam(\"PRIMEM\")\n self.gcs_unit = self._getgcsparam(\"UNIT\")\n self.projection = self._gettxt('PROJECTION[\"', '\"')\n self.latitude_of_origin = self._getvalue(\"latitude_of_origin\")\n self.central_meridian = self._getvalue(\"central_meridian\")\n self.standard_parallel_1 = self._getvalue(\"standard_parallel_1\")\n self.standard_parallel_2 = self._getvalue(\"standard_parallel_2\")\n self.scale_factor = self._getvalue(\"scale_factor\")\n self.false_easting = self._getvalue(\"false_easting\")\n self.false_northing = self._getvalue(\"false_northing\")\n self.projcs_unit = self._getprojcs_unit()\n\n def _gettxt(self, s1, s2):\n s = self.wktstr.lower()\n strt = s.find(s1.lower())\n if strt >= 0: # -1 indicates not found\n strt += len(s1)\n end = s[strt:].find(s2.lower()) + strt\n return self.wktstr[strt:end]\n\n def _getvalue(self, k):\n s = self.wktstr.lower()\n strt = s.find(k.lower())\n if strt >= 0:\n strt += len(k)\n end = s[strt:].find(\"]\") + strt\n try:\n return float(self.wktstr[strt:end].split(\",\")[1])\n except:\n print(\" could not typecast wktstr to a float\")\n\n def _getgcsparam(self, txt):\n nvalues = 3 if txt.lower() == \"spheroid\" else 2\n tmp = self._gettxt('{}[\"'.format(txt), \"]\")\n if tmp is not None:\n tmp = tmp.replace('\"', \"\").split(\",\")\n name = tmp[0:1]\n values = list(map(float, tmp[1:nvalues]))\n return name + values\n else:\n return [None] * nvalues\n\n def _getprojcs_unit(self):\n if self.projcs is not None:\n tmp = self.wktstr.lower().split('unit[\"')[-1]\n uname, ufactor = tmp.strip().strip(\"]\").split('\",')[0:2]\n ufactor = float(ufactor.split(\"]\")[0].split()[0].split(\",\")[0])\n return uname, ufactor\n return None, None\n\n\ndef getprj(epsg, addlocalreference=True, text=\"esriwkt\"):\n \"\"\"\n Gets projection file (.prj) text for given epsg code from\n spatialreference.org\n\n .. deprecated:: 3.2.11\n This function will be removed in version 3.3.5. Use\n :py:class:`flopy.discretization.structuredgrid.StructuredGrid` instead.\n\n Parameters\n ----------\n epsg : int\n epsg code for coordinate system\n addlocalreference : boolean\n adds the projection file text associated with epsg to a local\n database, epsgref.json, located in the user's data directory.\n\n References\n ----------\n https://www.epsg-registry.org/\n\n Returns\n -------\n prj : str\n text for a projection (*.prj) file.\n\n \"\"\"\n warnings.warn(\n \"SpatialReference has been deprecated and will be removed in version \"\n \"3.3.5. Use StructuredGrid instead.\",\n category=DeprecationWarning,\n )\n epsgfile = epsgRef()\n wktstr = epsgfile.get(epsg)\n if wktstr is None:\n wktstr = get_spatialreference(epsg, text=text)\n if addlocalreference and wktstr is not None:\n epsgfile.add(epsg, wktstr)\n return wktstr\n\n\ndef get_spatialreference(epsg, text=\"esriwkt\"):\n \"\"\"\n Gets text for given epsg code and text format from spatialreference.org\n\n Fetches the reference text using the url:\n https://spatialreference.org/ref/epsg/<epsg code>/<text>/\n\n See: https://www.epsg-registry.org/\n\n .. deprecated:: 3.2.11\n This function will be removed in version 3.3.5. Use\n :py:class:`flopy.discretization.structuredgrid.StructuredGrid` instead.\n\n Parameters\n ----------\n epsg : int\n epsg code for coordinate system\n text : str\n string added to url\n\n Returns\n -------\n url : str\n\n \"\"\"\n from flopy.utils.flopy_io import get_url_text\n\n warnings.warn(\n \"SpatialReference has been deprecated and will be removed in version \"\n \"3.3.5. Use StructuredGrid instead.\",\n category=DeprecationWarning,\n )\n\n epsg_categories = [\"epsg\", \"esri\"]\n for cat in epsg_categories:\n url = \"{}/ref/{}/{}/{}/\".format(srefhttp, cat, epsg, text)\n result = get_url_text(url)\n if result is not None:\n break\n if result is not None:\n return result.replace(\"\\n\", \"\")\n elif result is None and text != \"epsg\":\n for cat in epsg_categories:\n error_msg = (\n \"No internet connection or \"\n + \"epsg code {} \".format(epsg)\n + \"not found at {}/ref/\".format(srefhttp)\n + \"{}/{}/{}\".format(cat, cat, epsg)\n )\n print(error_msg)\n # epsg code not listed on spatialreference.org\n # may still work with pyproj\n elif text == \"epsg\":\n return \"epsg:{}\".format(epsg)\n\n\ndef getproj4(epsg):\n \"\"\"\n Get projection file (.prj) text for given epsg code from\n spatialreference.org. See: https://www.epsg-registry.org/\n\n .. deprecated:: 3.2.11\n This function will be removed in version 3.3.5. Use\n :py:class:`flopy.discretization.structuredgrid.StructuredGrid` instead.\n\n Parameters\n ----------\n epsg : int\n epsg code for coordinate system\n\n Returns\n -------\n prj : str\n text for a projection (*.prj) file.\n\n \"\"\"\n warnings.warn(\n \"SpatialReference has been deprecated and will be removed in version \"\n \"3.3.5. Use StructuredGrid instead.\",\n category=DeprecationWarning,\n )\n\n return get_spatialreference(epsg, text=\"proj4\")\n" ]
[ [ "numpy.tile", "numpy.where", "numpy.cos", "numpy.max", "numpy.sin", "numpy.empty", "numpy.add.reduce", "scipy.ndimage.rotate", "matplotlib.pyplot.subplots", "numpy.nanmin", "numpy.arange", "matplotlib.pyplot.gca", "numpy.nanmax", "numpy.array", "numpy.savetxt", "matplotlib.collections.QuadMesh", "numpy.zeros", "numpy.reshape", "matplotlib.pyplot.close", "numpy.isscalar", "numpy.isnan", "numpy.add.accumulate", "numpy.ones", "numpy.abs", "numpy.meshgrid", "numpy.unique" ] ]
elhamalamoudi/deepPID
[ "a6b80abeebda3c86fd99dc37805977e8994b6c36" ]
[ "robots.py" ]
[ "import rospy\nfrom nav_msgs.msg import Odometry\nfrom geometry_msgs.msg import Twist\nimport numpy as np\nimport tf.transformations\nfrom plotter import plotter\nfrom pid import pi_controller_pioneer, pid_controller_pioneer\nfrom std_srvs.srv import Empty\n#TODO nothing is stored here yet. So no plots will be abailable to the user. \n\n\nALPHA = 0.1\n\n\nclass pioneer_pi():\n\n def __init__(self, name = \"pioneer\", n_actions=4, controller_type='pi',save_image=False, dt = 0.1, Teval = 1., simulation = True,reset=False, ep_length=100):\n\n\n self.dt = dt\n self.Teval = Teval\n self.execution = np.divide(self.Teval,self.dt).astype(int)\n self.pos = np.zeros(2)\n self.vel_v = np.zeros(3)\n self.vel_w = np.zeros(3)\n self.vel = np.zeros(2)\n self.velocities = np.zeros((self.execution,2))\n self.reading = False\n self.euler = np.zeros(3)\n self.Quater = np.zeros(4)\n self.done = False\n self.error = np.zeros((3,2))\n self.u0 = np.zeros(2)\n self.u = np.zeros(2)\n self.n_actions = n_actions\n self.action = np.zeros(self.n_actions)\n self.set_point = np.zeros(2)\n self.ep_length = ep_length\n self.node = rospy.init_node('DQPID', anonymous=False)\n if simulation: \n self.Publisher = rospy.Publisher(\"/sim_p3at/cmd_vel\", Twist, queue_size=1)\n self.Subscriber = rospy.Subscriber(\"/sim_p3at/odom\", Odometry, self.callback_pose, queue_size=1)\n else: \n self.Publisher = rospy.Publisher(\"/RosAria/cmd_vel\", Twist, queue_size=1)\n self.Subscriber = rospy.Subscriber(\"/RosAria/pose\", Odometry, self.callback_pose, queue_size=1) \n\n self.rate = rospy.Rate(10.) # 10hz\n self.msg = Twist()\n self.action_vx = np.zeros(2)\n self.action_wz = np.zeros(2)\n self.reward = -1.\n self.temporal_vx = np.zeros(self.execution)\n self.temporal_wz = np.zeros(self.execution)\n self.controller_type = controller_type\n\n if self.controller_type == 'pi':\n self.controller = pi_controller_pioneer(set_point=self.set_point, dt=self.dt)\n else: \n self.controller = pid_controller_pioneer(set_point=self.set_point, dt=self.dt)\n # to plot\n # to plot\n self.save_image = save_image\n self.acc = np.zeros(1)\n self.thruster = np.zeros(1)\n if self.save_image: \n self.plots_counter = 0\n self.plot = plotter()\n self.plot.update(self.vel,self.action,self.pos,self.u)\n self.time = 0. \n self.reset_simulation= reset\n self.reset_world = rospy.ServiceProxy('/gazebo/reset_world', Empty) \n\n def reset(self):\n self.reading = False\n self.u = np.zeros(2)\n self.reward = 0.\n self.done = False\n self.velocities = np.zeros((10,2))\n for j in range(50):\n self.msg.linear.x = 0.\n self.msg.angular.z = 0.\n self.Publisher.publish(self.msg)\n self.rate.sleep()\n if self.reset_simulation:\n self.reset_world()\n #while not self.reading:\n # self.rate.sleep(0.1)\n if self.save_image: \n self.plot.reset()\n self.plot.update(self.vel,self.action,self.pos,self.thruster)\n self.plots_counter = self.plots_counter + 1\n\n return self.pos, self.velocities, self.u \n\n \n\n def run(self, actions):\n\n self.controller.update_action(actions)\n # to plot\n self.action = actions\n \n for i in range(self.execution):\n \n self.u = self.controller.update(self.vel)\n self.u = np.clip(self.u, -0.8, 0.8)\n self.u0 = self.u\n # send msg\n self.msg.linear.x = self.u[0]\n self.msg.angular.z = self.u[1]\n self.Publisher.publish(self.msg)\n\n \n self.time = self.time + self.dt\n self.velocities[i] = self.vel\n # to keep sampling rate\n self.rate.sleep()\n \n \n # plot\n if self.save_image: self.plot.update(self.vel,self.action,self.pos,self.thruster)\n\n return self.pos, self.velocities, self.u\n\n def get_set_point(self, set_point):\n self.set_point = set_point\n self.controller.set_point = set_point\n\n\n def get_gaussian_reward(self, state, set_point, step):\n\n beta = self.n_actions*0.025 \n self.reward = -1.5 + beta\n \n v0 = [_[0] for _ in self.velocities] \n v1 = [_[1] for _ in self.velocities] \n v0 = np.mean(v0) + np.std(v0)\n v1 = np.mean(v1) + np.std(v1)\n v_weight = [1.,1.5]\n velocity = np.array([v0,v1])\n e_weight = 0.9*np.array([0.02, 0.02]) # np.array([0.02,0.02,0.02,0.02,0.02,0.02])*0.25\n for x in range(len(set_point)):\n diff = (velocity[x] - set_point[x])**2\n exponent = (diff/(e_weight[x]**2))\n self.reward = self.reward + v_weight[x]*np.exp(-0.5*exponent)\n\n \n # self.reward = self.reward - beta*np.sum(np.abs(action))\n \n if np.abs(self.vel[0])>1.:\n self.done = True\n elif np.abs(self.vel[1])>1.:\n self.done = True\n elif np.abs(self.euler[0]) > 0.5:\n self.done = True\n elif np.abs(self.euler[1]) > 0.5:\n self.done = True\n else: \n self.done = False\n\n if step >= self.ep_length:\n self.done = True\n\n\n return self.reward, self.done\n\n def get_reward_v2(self, state, velocity_req, step):\n velocity = self.velocities[9]\n self.reward = -1.\n # x, y, z, roll, pitch, yaw\n v_weight = [1.,1.]\n e_weight = 0.4*np.array([0.04, 0.04])\n for x in range(len(velocity_req)):\n diff = (velocity[x] - velocity_req[x])**2\n exponent = (diff/(e_weight[x]**2))\n self.reward = self.reward + v_weight[x]*np.exp(-0.5*exponent)\n\n if np.abs(self.vel[0])>1.:\n self.reward = -10.\n self.done = True\n elif np.abs(self.vel[1])>1.:\n self.reward = -10.\n self.done = True\n elif np.abs(self.euler[0]) > 0.5:\n self.reward = -1.\n self.done = True\n elif np.abs(self.euler[1]) > 0.5:\n self.reward = -1.\n self.done = True\n else: \n self.done = False\n\n if step >= self.ep_length:\n self.done = True\n\n return self.reward, self.done\n\n\n\n def plot_if(self):\n if self.save_image: \n self.plot_imgs()\n \n def plot_imgs(self):\n self.plot.plot(self.plots_counter)\n\n def wrapToPi(self, angles):\n \n if angles > np.pi:\n angles = angles - 2*np.pi\n elif angles < -np.pi:\n angles = angles + 2*np.pi\n return angles \n\n\n def callback_pose(self, msg_odometry):\n self.reading = True\n x = msg_odometry.pose.pose.position.x\n y = msg_odometry.pose.pose.position.y\n z = msg_odometry.pose.pose.position.z\n self.pos = np.array([x, y])\n\n vx = msg_odometry.twist.twist.linear.x\n vy = msg_odometry.twist.twist.linear.y\n vz = msg_odometry.twist.twist.linear.z\n self.vel_v = np.array([vx, vy, vz])\n wx = msg_odometry.twist.twist.angular.x\n wy = msg_odometry.twist.twist.angular.y\n wz = msg_odometry.twist.twist.angular.z\n self.vel_w = np.array([wx, wy, wz])\n\n Qx = msg_odometry.pose.pose.orientation.x\n Qy = msg_odometry.pose.pose.orientation.y\n Qz = msg_odometry.pose.pose.orientation.z\n Qw = msg_odometry.pose.pose.orientation.w\n #z y x representation\n #Quater=[Qz,Qy,Qx,Qw];\n #Quater = np.array([Qw,Qx,Qy,Qz]) # este es el que eestaba usando\n self.Quater = np.array([Qx,Qy,Qz, Qw])\n #z y x representation of quaternions\n euler_original = tf.transformations.euler_from_quaternion(self.Quater) #[rad]\n \n self.euler = [ self.wrapToPi(_) for _ in euler_original] \n # print(np.round(self.euler,3))\n #self.velocity = np.array([vx, wz])\n a = 0.9*self.vel[0] + 0.1*vx\n b = 0.9*self.vel[1] + 0.1*wz\n # print('a',a)\n self.vel = np.array([a, b])\n # self.vel = np.array([vx, wz])\n\n\n def stop(self):\n self.msg.linear.x = 0.\n self.msg.angular.z = 0.\n self.Publisher.publish(self.msg)" ]
[ [ "numpy.divide", "numpy.array", "numpy.zeros", "numpy.exp", "numpy.mean", "numpy.std", "numpy.abs", "numpy.clip" ] ]
dsblank/pytorch-lightning
[ "ed26c177b2c1d93c800dc8f83ffe69ce999c11db" ]
[ "tests/models/mixins.py" ]
[ "from collections import OrderedDict\n\nimport torch\n\nfrom pytorch_lightning.core.decorators import data_loader\n\n\nclass LightningValidationStepMixin:\n \"\"\"\n Add val_dataloader and validation_step methods for the case\n when val_dataloader returns a single dataloader\n \"\"\"\n\n @data_loader\n def val_dataloader(self):\n return self._dataloader(train=False)\n\n def validation_step(self, batch, batch_idx):\n \"\"\"\n Lightning calls this inside the validation loop\n :param batch:\n :return:\n \"\"\"\n x, y = batch\n x = x.view(x.size(0), -1)\n y_hat = self.forward(x)\n\n loss_val = self.loss(y, y_hat)\n\n # acc\n labels_hat = torch.argmax(y_hat, dim=1)\n val_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)\n val_acc = torch.tensor(val_acc)\n\n if self.on_gpu:\n val_acc = val_acc.cuda(loss_val.device.index)\n\n # in DP mode (default) make sure if result is scalar, there's another dim in the beginning\n if self.trainer.use_dp:\n loss_val = loss_val.unsqueeze(0)\n val_acc = val_acc.unsqueeze(0)\n\n # alternate possible outputs to test\n if batch_idx % 1 == 0:\n output = OrderedDict({\n 'val_loss': loss_val,\n 'val_acc': val_acc,\n })\n return output\n if batch_idx % 2 == 0:\n return val_acc\n\n if batch_idx % 3 == 0:\n output = OrderedDict({\n 'val_loss': loss_val,\n 'val_acc': val_acc,\n 'test_dic': {'val_loss_a': loss_val}\n })\n return output\n\n\nclass LightningValidationMixin(LightningValidationStepMixin):\n \"\"\"\n Add val_dataloader, validation_step, and validation_end methods for the case\n when val_dataloader returns a single dataloader\n \"\"\"\n\n def validation_end(self, outputs):\n \"\"\"\n Called at the end of validation to aggregate outputs\n :param outputs: list of individual outputs of each validation step\n :return:\n \"\"\"\n # if returned a scalar from validation_step, outputs is a list of tensor scalars\n # we return just the average in this case (if we want)\n # return torch.stack(outputs).mean()\n val_loss_mean = 0\n val_acc_mean = 0\n for output in outputs:\n val_loss = output['val_loss']\n\n # reduce manually when using dp\n if self.trainer.use_dp or self.trainer.use_ddp2:\n val_loss = torch.mean(val_loss)\n val_loss_mean += val_loss\n\n # reduce manually when using dp\n val_acc = output['val_acc']\n if self.trainer.use_dp or self.trainer.use_ddp2:\n val_acc = torch.mean(val_acc)\n\n val_acc_mean += val_acc\n\n val_loss_mean /= len(outputs)\n val_acc_mean /= len(outputs)\n\n tqdm_dict = {'val_loss': val_loss_mean.item(), 'val_acc': val_acc_mean.item()}\n results = {'progress_bar': tqdm_dict, 'log': tqdm_dict}\n return results\n\n\nclass LightningValidationStepMultipleDataloadersMixin:\n \"\"\"\n Add val_dataloader and validation_step methods for the case\n when val_dataloader returns multiple dataloaders\n \"\"\"\n\n @data_loader\n def val_dataloader(self):\n return [self._dataloader(train=False), self._dataloader(train=False)]\n\n def validation_step(self, batch, batch_idx, dataloader_idx):\n \"\"\"\n Lightning calls this inside the validation loop\n :param batch:\n :return:\n \"\"\"\n x, y = batch\n x = x.view(x.size(0), -1)\n y_hat = self.forward(x)\n\n loss_val = self.loss(y, y_hat)\n\n # acc\n labels_hat = torch.argmax(y_hat, dim=1)\n val_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)\n val_acc = torch.tensor(val_acc)\n\n if self.on_gpu:\n val_acc = val_acc.cuda(loss_val.device.index)\n\n # in DP mode (default) make sure if result is scalar, there's another dim in the beginning\n if self.trainer.use_dp:\n loss_val = loss_val.unsqueeze(0)\n val_acc = val_acc.unsqueeze(0)\n\n # alternate possible outputs to test\n if batch_idx % 1 == 0:\n output = OrderedDict({\n 'val_loss': loss_val,\n 'val_acc': val_acc,\n })\n return output\n if batch_idx % 2 == 0:\n return val_acc\n\n if batch_idx % 3 == 0:\n output = OrderedDict({\n 'val_loss': loss_val,\n 'val_acc': val_acc,\n 'test_dic': {'val_loss_a': loss_val}\n })\n return output\n if batch_idx % 5 == 0:\n output = OrderedDict({\n f'val_loss_{dataloader_idx}': loss_val,\n f'val_acc_{dataloader_idx}': val_acc,\n })\n return output\n\n\nclass LightningValidationMultipleDataloadersMixin(LightningValidationStepMultipleDataloadersMixin):\n \"\"\"\n Add val_dataloader, validation_step, and validation_end methods for the case\n when val_dataloader returns multiple dataloaders\n \"\"\"\n\n def validation_end(self, outputs):\n \"\"\"\n Called at the end of validation to aggregate outputs\n :param outputs: list of individual outputs of each validation step\n :return:\n \"\"\"\n # if returned a scalar from validation_step, outputs is a list of tensor scalars\n # we return just the average in this case (if we want)\n # return torch.stack(outputs).mean()\n val_loss_mean = 0\n val_acc_mean = 0\n i = 0\n for dl_output in outputs:\n for output in dl_output:\n val_loss = output['val_loss']\n\n # reduce manually when using dp\n if self.trainer.use_dp:\n val_loss = torch.mean(val_loss)\n val_loss_mean += val_loss\n\n # reduce manually when using dp\n val_acc = output['val_acc']\n if self.trainer.use_dp:\n val_acc = torch.mean(val_acc)\n\n val_acc_mean += val_acc\n i += 1\n\n val_loss_mean /= i\n val_acc_mean /= i\n\n tqdm_dict = {'val_loss': val_loss_mean.item(), 'val_acc': val_acc_mean.item()}\n result = {'progress_bar': tqdm_dict}\n return result\n\n\nclass LightningTestStepMixin:\n\n @data_loader\n def test_dataloader(self):\n return self._dataloader(train=False)\n\n def test_step(self, batch, batch_idx):\n \"\"\"\n Lightning calls this inside the validation loop\n :param batch:\n :return:\n \"\"\"\n x, y = batch\n x = x.view(x.size(0), -1)\n y_hat = self.forward(x)\n\n loss_test = self.loss(y, y_hat)\n\n # acc\n labels_hat = torch.argmax(y_hat, dim=1)\n test_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)\n test_acc = torch.tensor(test_acc)\n\n if self.on_gpu:\n test_acc = test_acc.cuda(loss_test.device.index)\n\n # in DP mode (default) make sure if result is scalar, there's another dim in the beginning\n if self.trainer.use_dp:\n loss_test = loss_test.unsqueeze(0)\n test_acc = test_acc.unsqueeze(0)\n\n # alternate possible outputs to test\n if batch_idx % 1 == 0:\n output = OrderedDict({\n 'test_loss': loss_test,\n 'test_acc': test_acc,\n })\n return output\n if batch_idx % 2 == 0:\n return test_acc\n\n if batch_idx % 3 == 0:\n output = OrderedDict({\n 'test_loss': loss_test,\n 'test_acc': test_acc,\n 'test_dic': {'test_loss_a': loss_test}\n })\n return output\n\n\nclass LightningTestMixin(LightningTestStepMixin):\n def test_end(self, outputs):\n \"\"\"\n Called at the end of validation to aggregate outputs\n :param outputs: list of individual outputs of each validation step\n :return:\n \"\"\"\n # if returned a scalar from test_step, outputs is a list of tensor scalars\n # we return just the average in this case (if we want)\n # return torch.stack(outputs).mean()\n test_loss_mean = 0\n test_acc_mean = 0\n for output in outputs:\n test_loss = output['test_loss']\n\n # reduce manually when using dp\n if self.trainer.use_dp:\n test_loss = torch.mean(test_loss)\n test_loss_mean += test_loss\n\n # reduce manually when using dp\n test_acc = output['test_acc']\n if self.trainer.use_dp:\n test_acc = torch.mean(test_acc)\n\n test_acc_mean += test_acc\n\n test_loss_mean /= len(outputs)\n test_acc_mean /= len(outputs)\n\n tqdm_dict = {'test_loss': test_loss_mean.item(), 'test_acc': test_acc_mean.item()}\n result = {'progress_bar': tqdm_dict}\n return result\n\n\nclass LightningTestStepMultipleDataloadersMixin:\n\n @data_loader\n def test_dataloader(self):\n return [self._dataloader(train=False), self._dataloader(train=False)]\n\n def test_step(self, batch, batch_idx, dataloader_idx):\n \"\"\"\n Lightning calls this inside the validation loop\n :param batch:\n :return:\n \"\"\"\n x, y = batch\n x = x.view(x.size(0), -1)\n y_hat = self.forward(x)\n\n loss_test = self.loss(y, y_hat)\n\n # acc\n labels_hat = torch.argmax(y_hat, dim=1)\n test_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)\n test_acc = torch.tensor(test_acc)\n\n if self.on_gpu:\n test_acc = test_acc.cuda(loss_test.device.index)\n\n # in DP mode (default) make sure if result is scalar, there's another dim in the beginning\n if self.trainer.use_dp:\n loss_test = loss_test.unsqueeze(0)\n test_acc = test_acc.unsqueeze(0)\n\n # alternate possible outputs to test\n if batch_idx % 1 == 0:\n output = OrderedDict({\n 'test_loss': loss_test,\n 'test_acc': test_acc,\n })\n return output\n if batch_idx % 2 == 0:\n return test_acc\n\n if batch_idx % 3 == 0:\n output = OrderedDict({\n 'test_loss': loss_test,\n 'test_acc': test_acc,\n 'test_dic': {'test_loss_a': loss_test}\n })\n return output\n if batch_idx % 5 == 0:\n output = OrderedDict({\n f'test_loss_{dataloader_idx}': loss_test,\n f'test_acc_{dataloader_idx}': test_acc,\n })\n return output\n\n\nclass LightningTestMultipleDataloadersMixin(LightningTestStepMultipleDataloadersMixin):\n def test_end(self, outputs):\n \"\"\"\n Called at the end of validation to aggregate outputs\n :param outputs: list of individual outputs of each validation step\n :return:\n \"\"\"\n # if returned a scalar from test_step, outputs is a list of tensor scalars\n # we return just the average in this case (if we want)\n # return torch.stack(outputs).mean()\n test_loss_mean = 0\n test_acc_mean = 0\n i = 0\n for dl_output in outputs:\n for output in dl_output:\n test_loss = output['test_loss']\n\n # reduce manually when using dp\n if self.trainer.use_dp:\n test_loss = torch.mean(test_loss)\n test_loss_mean += test_loss\n\n # reduce manually when using dp\n test_acc = output['test_acc']\n if self.trainer.use_dp:\n test_acc = torch.mean(test_acc)\n\n test_acc_mean += test_acc\n i += 1\n\n test_loss_mean /= i\n test_acc_mean /= i\n\n tqdm_dict = {'test_loss': test_loss_mean.item(), 'test_acc': test_acc_mean.item()}\n result = {'progress_bar': tqdm_dict}\n return result\n" ]
[ [ "torch.mean", "torch.tensor", "torch.argmax", "torch.sum" ] ]
liusida/ds2_arxiv
[ "1ee8a3f65cfb662a1af6dca29cde3e07ec5b322b" ]
[ "ds2_arxiv/13.0.twitter.py" ]
[ "import socket, os, re, time\nimport pandas as pd\nimport numpy as np\nfrom ds2_arxiv.tools.my_firefox import MyFirefox\nfrom bs4 import BeautifulSoup\nimport random\n\nlocal_debug = socket.gethostname()!=\"star-lab\"\n\ndef google_search(author):\n author = author.lower()\n f_author = author.replace(\" \", \"_\")\n filename = f\"data/twitter/{f_author}.txt\"\n bad_filename = f\"data/twitter_bad/{f_author}.html\"\n if os.path.exists(filename) or os.path.exists(bad_filename):\n return\n search = author.replace(\" \", \"+\")\n url = f\"https://www.google.com/search?q={search}+Twitter+Account&ei={random.getrandbits(32)}\"\n\n g_firefox = MyFirefox(proxy_txt_filename=\"config/vip.proxy.txt\", proxy_disabled=local_debug)\n html = g_firefox.get(url)\n if html is None:\n print(\"google search> html is None\")\n g_firefox.reset()\n time.sleep(10)\n return\n\n soup = BeautifulSoup(html, 'html.parser')\n search_result = soup.find('div', {\"id\":'search'})\n if search_result is None:\n print(\"google search> Oh, no! I've been caught!\")\n with open(\"tmp_caught.html\", \"w\") as f:\n print(soup.text, file=f)\n g_firefox.reset()\n time.sleep(30)\n return\n \n line = search_result.find('h3', text=lambda t: t and 'Twitter' in t and re.search(r'\\(@.+\\)', t))\n if line:\n with open(filename, 'w') as f:\n print(author, file=f)\n print(line.text, file=f)\n print(f\"wrote {filename}\")\n else:\n with open(bad_filename, 'w') as f:\n print(html, file=f)\n print(f\"bad {bad_filename}\")\n\ndef bing_search(author):\n author = author.lower()\n f_author = author.replace(\" \", \"_\")\n filename = f\"data/twitter/{f_author}.txt\"\n bad_filename = f\"data/twitter_bad/{f_author}.html\"\n if os.path.exists(filename) or os.path.exists(bad_filename):\n return\n search = author.replace(\" \", \"%20\")\n url = f\"https://www.bing.com/search?q={search}%20Twitter\"\n\n print(f\"getting {url}\")\n g_firefox = MyFirefox(proxy_txt_filename=\"config/vip.proxy.txt\", proxy_disabled=local_debug)\n html = g_firefox.get(url)\n if html is None:\n print(\"bing search> html is None\")\n g_firefox.reset()\n time.sleep(10)\n return\n\n soup = BeautifulSoup(html, 'html.parser')\n search_result = soup.find('ol', {\"id\":'b_results'})\n if search_result is None:\n print(\"bing search> Oh, no! I've been caught!\")\n with open(\"tmp_caught.html\", \"w\") as f:\n print(soup.text, file=f)\n g_firefox.reset()\n time.sleep(10)\n return\n \n h2s = search_result.find_all('h2')\n for h2 in h2s:\n t = h2.text\n if 'Twitter' in t and '@' in t:\n with open(filename, 'w') as f:\n print(author, file=f)\n print(t, file=f)\n print(f\"wrote {filename}\")\n return True\n with open(bad_filename, 'w') as f:\n print(html, file=f)\n print(f\"bad {bad_filename}\")\n\ndef main():\n df = pd.read_pickle(\"shared/arxiv_4422.pickle\")\n df = df.sample(frac=1).reset_index(drop=True)\n\n for index, row in df.iterrows():\n title = row['title']\n first_author = row['first_author']\n last_author = row['last_author']\n other_authors = []\n _list = row['other_authors'].split(\":|:\")\n _list.append(first_author)\n _list.append(last_author)\n print(\"\\n\",title)\n for _author in _list:\n if _author==\"\":\n continue\n bing_search(_author)\n\n\nif __name__==\"__main__\":\n main()\n # google_search(\"tsung-hsien wen\")" ]
[ [ "pandas.read_pickle" ] ]
cannlytics/cannabis-data-science
[ "1d5f3085e7b2858b6791840b90335be4669268b3" ]
[ "2021-11-24/retailer_stats_ma.py" ]
[ "\"\"\"\nMassachusetts Cannabis Dispensary Statistics\nCopyright (c) 2021 Cannlytics and the Cannabis Data Science Meetup Group\n\nAuthors: Keegan Skeate <[email protected]>\nCreated: 11/24/2021\nUpdated: 11/24/2021\nLicense: MIT License <https://opensource.org/licenses/MIT>\n\nObjective:\n \n Calculate the following statistics in Massachusetts:\n - Retailers per 100,000 adults\n - Revenue per retailer\n \nData Sources:\n \n MA Cannabis Control Commission\n - Approved Massachusetts Licensees: https://dev.socrata.com/foundry/opendata.mass-cannabis-control.com/hmwt-yiqy\n - Plant Activity and Volume: https://dev.socrata.com/foundry/opendata.mass-cannabis-control.com/j3q7-3usu\n\"\"\"\nfrom dotenv import dotenv_values\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport requests\n\n# Internal imports\nfrom utils import (\n end_of_period_timeseries,\n reverse_dataframe,\n)\n\n#--------------------------------------------------------------------------\n# Get MA public cannabis data.\n#--------------------------------------------------------------------------\n\n# Setup Socrata API, setting the App Token for request headers.\nconfig = dotenv_values('../.env')\napp_token = config.get('APP_TOKEN', None)\nheaders = {'X-App-Token': app_token}\nbase = 'https://opendata.mass-cannabis-control.com/resource'\n\n# Get licensees data.\nurl = f'{base}/hmwt-yiqy.json'\nparams = {'$limit': 10000, '$order': 'app_create_date DESC'}\nresponse = requests.get(url, headers=headers, params=params)\nlicensees = pd.DataFrame(response.json(), dtype=float)\n\n# Get production stats (total employees, total plants, etc.) j3q7-3usu\nurl = f'{base}/j3q7-3usu.json'\nparams = {'$limit': 2000, '$order': 'activitysummarydate DESC'}\nresponse = requests.get(url, headers=headers, params=params)\nproduction = pd.DataFrame(response.json(), dtype=float)\nproduction = reverse_dataframe(production)\nproduction['date'] = pd.to_datetime(production['activitysummarydate'])\nproduction.set_index('date', inplace=True)\n\n# Calculate sales difference, coding outliers and negatives as 0.\nproduction['sales'] = production['salestotal'].diff()\noutlier = production.loc[production.sales >= 10000000]\nproduction.at[outlier.index, 'sales'] = 0\nnegatives = production.loc[production.sales < 0]\nproduction.at[negatives.index, 'sales'] = 0\n\n#--------------------------------------------------------------------------\n# Re-look at weekly averages using only licensees with final licenses.\n#--------------------------------------------------------------------------\n\n# Identify licensees with final licenses.\n# These are the licenses that are assumed to be currently operating.\nfinal_licensees = licensees.loc[\n (licensees['approved_license_type'] == 'FINAL LICENSE')\n]\n\n# Create weekly series.\nweekly_sales = production.sales.resample('W-SUN').sum()\nweekly_plants = production['total_plantfloweringcount'].resample('W-SUN').mean()\nweekly_employees = production.total_employees.resample('W-SUN').mean()\n\n# Create total licensees series.\nproduction['total_retailers'] = 0\nproduction['total_cultivators'] = 0\nproduction['total_licensees'] = 0\nfor index, _ in production.iterrows():\n timestamp = index.isoformat()\n production.at[index, 'total_retailers'] = len(licensees.loc[\n (licensees.license_type == 'Marijuana Retailer') &\n (licensees['cnb_dt_of_final_licensure'] <= timestamp)\n ])\n production.at[index, 'total_cultivators'] = len(licensees.loc[\n (licensees.license_type == 'Marijuana Cultivator') &\n (licensees['cnb_dt_of_final_licensure'] <= timestamp)\n ])\n production.at[index, 'total_licensees'] = len(licensees.loc[\n (licensees['cnb_dt_of_final_licensure'] <= timestamp)\n ])\n\n# Create weekly averages.\nweekly_total_retailers = production['total_retailers'].resample('W-SUN').mean()\nweekly_total_cultivators = production['total_cultivators'].resample('W-SUN').mean()\nweekly_total_licensees = production['total_licensees'].resample('W-SUN').mean()\n\n# Estimate sales per retailer.\nsales_per_retailer = weekly_sales / weekly_total_retailers\n(sales_per_retailer / 1000).plot()\nplt.show()\n\n# Estimate plants per cultivator.\nplants_per_cultivator = weekly_plants / weekly_total_cultivators\nplants_per_cultivator.plot()\nplt.show()\n\n# Estimate employees per licensee.\nemployees_per_license = weekly_employees / weekly_total_licensees\nemployees_per_license.plot()\nplt.show()\n\n# Calculate sales per retailer in 2020.\navg_2020_sales = sales_per_retailer.loc[\n (sales_per_retailer.index >= pd.to_datetime('2020-01-01')) &\n (sales_per_retailer.index < pd.to_datetime('2021-01-01'))\n].sum()\nprint('Sales per retailer in MA in 2020: %.2fM' % (avg_2020_sales / 1_000_000))\n\n#--------------------------------------------------------------------------\n# Calculate retailers per population.\n#--------------------------------------------------------------------------\nfrom fredapi import Fred\n\n# Initialize FRED API client.\nfred_api_key = config.get('FRED_API_KEY')\nfred = Fred(api_key=fred_api_key)\n\n# Get MA population (conjecturing that population remains constant in 2021).\nobservation_start = production.index.min().isoformat()\npopulation = fred.get_series('MAPOP', observation_start=observation_start)\npopulation = end_of_period_timeseries(population, 'Y')\npopulation = population.multiply(1000) # thousands of people\nnew_row = pd.DataFrame([population[-1]], index=[pd.to_datetime('2021-12-31')])\npopulation = pd.concat([population, pd.DataFrame(new_row)], ignore_index=False)\n\n# Calculate retailers per population.\nweekly_population = population[0].resample('W-SUN').mean().pad()\nretailers_per_capita = weekly_total_retailers / (weekly_population / 100_000)\nretailers_per_capita.plot()\n\n# Calculate retailers per capita in 2020.\navg_retailers_per_capita_2020 = retailers_per_capita.loc[\n (retailers_per_capita.index >= pd.to_datetime('2020-01-01')) &\n (retailers_per_capita.index < pd.to_datetime('2021-01-01'))\n].mean()\nprint('Retailres per capita in MA in 2020: %.2f' % avg_retailers_per_capita_2020)\n" ]
[ [ "pandas.to_datetime", "matplotlib.pyplot.show", "pandas.DataFrame" ] ]
zhongyuchen/information-extraction
[ "6cf9905bed5ee9c33706854cd6ceae04194aa5e4" ]
[ "classification/model_bert.py" ]
[ "import torch\nfrom torch import nn\n# from torch.nn import CrossEntropyLosss\n\nimport os\nimport json\n\nfrom fastNLP.modules.encoder.bert import BertModel, BertEmbeddings, BertEncoder, BertPooler, BertLayerNorm\n\nCONFIG_FILE = 'bert_config.json'\n\n\n# fastNLP formated class based on BertModel\nclass BertForMultiLabelSequenceClassification(nn.Module):\n \"\"\"BERT(Bidirectional Embedding Representations from Transformers).\n\n 如果你想使用预训练好的权重矩阵,请在以下网址下载.\n sources::\n\n 'bert-base-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased.tar.gz\",\n 'bert-large-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased.tar.gz\",\n 'bert-base-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased.tar.gz\",\n 'bert-large-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased.tar.gz\",\n 'bert-base-multilingual-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased.tar.gz\",\n 'bert-base-multilingual-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased.tar.gz\",\n 'bert-base-chinese': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese.tar.gz\",\n\n\n 用预训练权重矩阵来建立BERT模型::\n\n model = BertModel.from_pretrained(\"path/to/weights/directory\")\n\n 用随机初始化权重矩阵来建立BERT模型::\n\n model = BertModel()\n\n :param int vocab_size: 词表大小,默认值为30522,为BERT English uncase版本的词表大小\n :param int hidden_size: 隐层大小,默认值为768,为BERT base的版本\n :param int num_hidden_layers: 隐藏层数,默认值为12,为BERT base的版本\n :param int num_attention_heads: 多头注意力头数,默认值为12,为BERT base的版本\n :param int intermediate_size: FFN隐藏层大小,默认值是3072,为BERT base的版本\n :param str hidden_act: FFN隐藏层激活函数,默认值为``gelu``\n :param float hidden_dropout_prob: FFN隐藏层dropout,默认值为0.1\n :param float attention_probs_dropout_prob: Attention层的dropout,默认值为0.1\n :param int max_position_embeddings: 最大的序列长度,默认值为512,\n :param int type_vocab_size: 最大segment数量,默认值为2\n :param int initializer_range: 初始化权重范围,默认值为0.02\n \"\"\"\n\n def __init__(self, vocab_size=30522,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02, num_labels=50, **kwargs):\n super(BertForMultiLabelSequenceClassification, self).__init__()\n self.embeddings = BertEmbeddings(vocab_size, hidden_size, max_position_embeddings,\n type_vocab_size, hidden_dropout_prob)\n self.encoder = BertEncoder(num_hidden_layers, hidden_size, num_attention_heads,\n attention_probs_dropout_prob, hidden_dropout_prob, intermediate_size,\n hidden_act)\n self.pooler = BertPooler(hidden_size)\n self.dropout = nn.Dropout(hidden_dropout_prob)\n self.classifier = nn.Linear(hidden_size, num_labels)\n self.initializer_range = initializer_range\n\n self.apply(self.init_bert_weights)\n\n def init_bert_weights(self, module):\n if isinstance(module, (nn.Linear, nn.Embedding)):\n # Slightly different from the TF version which uses truncated_normal for initialization\n # cf https://github.com/pytorch/pytorch/pull/5617\n module.weight.data.normal_(mean=0.0, std=self.initializer_range)\n elif isinstance(module, BertLayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, output_all_encoded_layers=True):\n if attention_mask is None:\n attention_mask = torch.ones_like(input_ids)\n if token_type_ids is None:\n token_type_ids = torch.zeros_like(input_ids)\n\n # We create a 3D attention mask from a 2D tensor mask.\n # Sizes are [batch_size, 1, 1, to_seq_length]\n # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]\n # this attention mask is more simple than the triangular masking of causal attention\n # used in OpenAI GPT, we just need to prepare the broadcast dimension here.\n extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)\n\n # Since attention_mask is 1.0 for positions we want to attend and 0.0 for\n # masked positions, this operation will create a tensor which is 0.0 for\n # positions we want to attend and -10000.0 for masked positions.\n # Since we are adding it to the raw scores before the softmax, this is\n # effectively the same as removing these entirely.\n extended_attention_mask = extended_attention_mask.to(dtype=next(self.parameters()).dtype) # fp16 compatibility\n extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0\n\n embedding_output = self.embeddings(input_ids, token_type_ids)\n encoded_layers = self.encoder(embedding_output,\n extended_attention_mask,\n output_all_encoded_layers=output_all_encoded_layers)\n sequence_output = encoded_layers[-1]\n pooled_output = self.pooler(sequence_output)\n if not output_all_encoded_layers:\n encoded_layers = encoded_layers[-1]\n\n # return encoded_layers, pooled_output\n pooled_output = self.dropout(pooled_output)\n logits = self.classifier(pooled_output)\n return {\"output\": logits}\n\n @classmethod\n def from_pretrained(cls, pretrained_model_dir, state_dict=None, *inputs, **kwargs):\n # Load config\n config_file = os.path.join(pretrained_model_dir, CONFIG_FILE)\n config = json.load(open(config_file, \"r\"))\n # config = BertConfig.from_json_file(config_file)\n # logger.info(\"Model config {}\".format(config))\n # Instantiate model.\n model = cls(*inputs, **config, **kwargs)\n if state_dict is None:\n weights_path = os.path.join(pretrained_model_dir, MODEL_WEIGHTS)\n state_dict = torch.load(weights_path)\n\n old_keys = []\n new_keys = []\n for key in state_dict.keys():\n new_key = None\n if 'gamma' in key:\n new_key = key.replace('gamma', 'weight')\n if 'beta' in key:\n new_key = key.replace('beta', 'bias')\n if new_key:\n old_keys.append(key)\n new_keys.append(new_key)\n for old_key, new_key in zip(old_keys, new_keys):\n state_dict[new_key] = state_dict.pop(old_key)\n\n missing_keys = []\n unexpected_keys = []\n error_msgs = []\n # copy state_dict so _load_from_state_dict can modify it\n metadata = getattr(state_dict, '_metadata', None)\n state_dict = state_dict.copy()\n if metadata is not None:\n state_dict._metadata = metadata\n\n def load(module, prefix=''):\n local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {})\n module._load_from_state_dict(\n state_dict, prefix, local_metadata, True, missing_keys, unexpected_keys, error_msgs)\n for name, child in module._modules.items():\n if child is not None:\n load(child, prefix + name + '.')\n\n load(model, prefix='' if hasattr(model, 'bert') else 'bert.')\n if len(missing_keys) > 0:\n print(\"Weights of {} not initialized from pretrained model: {}\".format(\n model.__class__.__name__, missing_keys))\n if len(unexpected_keys) > 0:\n print(\"Weights from pretrained model not used in {}: {}\".format(\n model.__class__.__name__, unexpected_keys))\n return model\n" ]
[ [ "torch.nn.Linear", "torch.nn.Dropout", "torch.ones_like", "torch.load", "torch.zeros_like" ] ]
marcusklasson/vcca_grocerystore
[ "c88483e3722a2508b866dbe4e67f4e7d2e10b92c" ]
[ "models/vcca_private/vcca_private_xw.py" ]
[ "\nimport tensorflow as tf\nimport numpy as np\n\nfrom models.networks.lstm_networks import language_generator, build_sampler, language_encoder\nfrom data.import_data import load_captions\n\nclass VCCA_private(object):\n\n def __init__(self, dim_x, dim_z, dim_w, word_to_idx, lambda_x=1.0, lambda_w=1.0,\n n_layers_encoder=1, n_layers_decoder=1, fc_hidden_size=512):\n \"\"\" VCCA_private for image features and text descriptions.\n\n Args:\n dim_x: Image feature dimension.\n dim_z: Latent representation dimension.\n dim_w: Text description dimension.\n dim_labels: Label dimension (number of classes).\n lambda_x: Scaling weights for image feature view. \n lambda_w: Scaling weights for text description view. \n lambda_y: Scaling weights for class label view. \n n_layers_encoder: Number of hidden layers in encoder. \n n_layers_decoder: Number of hidden layers in decoder.\n fc_hidden_size: Dimension in hidden fully-connected layers \n n_layers_classifier: Number of hidden layers in class label decoder.\n\n \"\"\"\n self.dim_x = dim_x\n self.dim_z = dim_z\n self.dim_w = dim_w\n self.dim_ux = dim_z\n self.dim_uw = dim_z \n # likelihood weighting terms\n self.lambda_x = lambda_x\n self.lambda_w = lambda_w\n self.n_layers_encoder = n_layers_encoder\n self.n_layers_decoder = n_layers_decoder\n self.fc_hidden_size = fc_hidden_size\n\n self.word_to_idx = word_to_idx\n self.idx_to_word = {i: w for w, i in word_to_idx.items()}\n\n self.V = len(word_to_idx) # Vocabulary size\n self.T = dim_w # Number of time steps in LSTM\n self.M = 256 # word embedding size\n self.H = dim_z # LSTM hidden state size\n \n self.x = tf.placeholder(tf.float32, [None, self.dim_x], name='x')\n self.captions = tf.placeholder(tf.int32, [None, self.T + 1], name='captions')\n\n # Other regularizers\n self.dropout_rate = tf.placeholder_with_default(1.0, shape=(), name='dropout_rate')\n self.kl_weight = tf.placeholder_with_default(1.0, shape=(), name='kl_weight') \n\n self.build_graph()\n print(\"VCCA_private_xw is initialized.\")\n\n def build_graph(self):\n \"\"\" Build computational graph.\n \"\"\"\n\n ### Encoder for shared latent variable z\n self.z_sample, self.z_mu, self.z_log_sigma_sq = self.get_encoder(self.x, name='variational/z')\n self.latent_rep = self.z_mu # Latent representation\n latent_rep = tf.identity(self.latent_rep, name='latent_rep') # for fetching tensor when restoring model!\n\n # Encoder for image feature private latent hx\n self.ux_sample, self.ux_mu, self.ux_log_sigma_sq = self.get_encoder(self.x, name='variational/ux')\n self.latent_rep_ux = self.ux_mu # Latent representation for natural image view\n latent_rep_ux = tf.identity(self.ux_mu, name='latent_rep_ux') # for fetching tensor when restoring model!\n\n # Encoder for image feature private latent hx\n self.uw_sample, self.uw_mu, self.uw_log_sigma_sq = self.get_text_encoder(self.captions,\n dim_z=self.dim_uw, \n name='variational/uw')\n self.latent_rep_uw = self.uw_mu # Latent representation for text description view\n latent_rep_uw = tf.identity(self.uw_mu, name='latent_rep_uw') # for fetching tensor when restoring model!\n\n ### Feature decoder \n self.x_recon = self.get_decoder(self.z_sample, y=self.ux_sample)\n image_feature_recon = tf.identity(self.x_recon, name='image_feature_recon') \n # Sum of squares loss\n self.x_rec_loss = tf.reduce_sum((self.x - self.x_recon)**2, 1) * self.lambda_x\n\n ### Text description decoder \n self.language_loss, self.all_h_train = self.get_text_loss(self.z_sample, y=self.uw_sample)\n # Categorical cross-entropy loss\n self.w_rec_loss = tf.reduce_sum(self.language_loss, 1) * self.lambda_w\n\n ### KL divergence and ELBO\n self.kl_div_z = self.kl_divergence(self.z_mu, self.z_log_sigma_sq) * self.kl_weight \n self.kl_div_ux = self.kl_divergence(self.ux_mu, self.ux_log_sigma_sq) \n self.kl_div_uw = self.kl_divergence(self.uw_mu, self.uw_log_sigma_sq) \n self.loss = -tf.reduce_mean(self.kl_div_z + self.x_rec_loss + self.w_rec_loss + self.kl_div_ux + self.kl_div_uw)\n\n ### Evaluation ###\n self.z_sample_eval, _, _ = self.get_encoder(self.x, name='variational/z', reuse = True)\n self.ux_sample_eval, _, _ = self.get_encoder(self.x, name='variational/ux', reuse = True)\n self.uw_sample_eval, _, _ = self.get_text_encoder(self.captions, dim_z=self.dim_uw, \n name='variational/uw', reuse = True)\n\n self.x_recon_eval = self.get_decoder( self.z_sample_eval, y=self.ux_sample_eval, reuse = True )\n self.sampled_captions, all_hidden = self.get_text_sampler(self.z_sample, y=self.uw_sample_eval, reuse=True)\n caption_sampler = tf.identity(self.sampled_captions, name='text_sampler')\n \n mask = tf.cast(tf.not_equal(tf.reduce_sum(all_hidden, axis=-1), 0), tf.float32)\n den = tf.expand_dims(tf.reduce_sum(mask, axis=-1), axis=1)\n self.text_rep = tf.reduce_sum(all_hidden, axis=1) / den \n\n ### Used in training feed_dict\n self.log_var = [self.loss, self.kl_div_z, self.x_rec_loss, self.w_rec_loss, self.kl_div_ux, self.kl_div_uw]\n self.val_log_var = self.log_var\n\n def get_encoder(self, x, y=None, name='variational', reuse=None):\n \"\"\" Build encoder for image features.\n \"\"\"\n with tf.variable_scope(name, reuse=reuse):\n\n if y is not None:\n x = tf.concat([x, y], 1)\n h = x\n for i in range(self.n_layers_encoder):\n h = tf.layers.dense(h, units=self.fc_hidden_size, activation=None, name='h' + str(i+1))\n h = tf.nn.leaky_relu(h)\n\n q_mu = tf.layers.dense(h, units=self.dim_z, activation=None, name='q_mu')\n q_logvar = tf.layers.dense(h, units=self.dim_z, activation=None, name='q_logvar')\n z_sample, q_mu, q_logvar = self.reparameterization_trick(q_mu, q_logvar)\n return z_sample, q_mu, q_logvar \n\n def get_decoder(self, z, y=None, reuse=None):\n \"\"\" Build decoder for image features.\n \"\"\"\n with tf.variable_scope('model', reuse=reuse):\n\n if y is not None:\n z = tf.concat([z, y], 1)\n h = z\n for i in range(self.n_layers_decoder):\n h = tf.layers.dense(h, units=self.fc_hidden_size, activation=None, name='h' + str(i+1))\n h = tf.nn.leaky_relu(h)\n x_recon = tf.layers.dense(h, units=self.dim_x, activation=None, name='x_recon')\n return x_recon\n\n def get_text_encoder(self, w, dim_z, name='variational', reuse=None):\n \"\"\" Build encoder for text descriptions.\n \"\"\"\n with tf.variable_scope(name, reuse=reuse):\n dim_h = self.H\n word_to_idx = self.word_to_idx\n T = self.T\n dim_emb = self.M\n\n self.all_hidden, self.final_hidden = language_encoder(w, word_to_idx, T, dim_h, dim_emb, reuse=None)\n\n #h = self.final_hidden # use final hidden states\n h = self._avg_hidden_states(self.all_hidden) #use average of hidden states\n q_mu = tf.layers.dense(h, units=dim_z, activation=None, name='q_mu')\n q_logvar = tf.layers.dense(h, units=dim_z, activation=None, name='q_logvar')\n z_sample, q_mu, q_logvar = self.reparameterization_trick(q_mu, q_logvar)\n return z_sample, q_mu, q_logvar\n\n def get_text_loss(self, z, y=None, reuse=None):\n \"\"\" Build decoder for text descriptions.\n \"\"\"\n captions = self.captions\n dim_h = self.H\n word_to_idx = self.word_to_idx\n T = self.T\n dim_emb = self.M\n dropout_rate = self.dropout_rate\n\n with tf.variable_scope('model', reuse=reuse):\n if y is not None:\n z = tf.concat([z, y], 1)\n #language_loss, h, _ = language_generator(z, captions, word_to_idx, T, dim_h, dim_emb, dropout_rate)\n language_loss, all_h = language_generator(z, captions, word_to_idx, T, dim_h, dim_emb, dropout_rate)\n return language_loss, all_h\n\n def get_text_sampler(self, z, y=None, reuse=True):\n \"\"\" Reusing decoder for sampling text descriptions.\n \"\"\"\n dim_h = self.H\n word_to_idx = self.word_to_idx\n T = self.T\n dim_emb = self.M\n\n with tf.variable_scope('model', reuse=reuse):\n if y is not None:\n z = tf.concat([z, y], 1)\n #generated_captions, h, _ = build_sampler(z, word_to_idx, dim_h, dim_emb, dropout_rate=1.0, max_len=16) \n generated_captions, all_h = build_sampler(z, word_to_idx, dim_h, dim_emb, dropout_rate=1.0, max_len=16) \n return generated_captions, all_h\n\n def reparameterization_trick(self, mu, log_sigma_sq):\n \"\"\"\n \"Reparameterization trick\"\n z = mu + sigma * epsilon\n \"\"\"\n epsilon = tf.random_normal((tf.shape(mu)), 0., 1. )\n sample = mu + tf.exp(0.5*log_sigma_sq) * epsilon\n return sample, mu, log_sigma_sq\n\n def _avg_hidden_states(self, all_h):\n \"\"\" Averaging hidden states to get representation for text description.\n \"\"\"\n mask = tf.cast(tf.not_equal(tf.reduce_sum(all_h, axis=-1), 0), tf.float32)\n den = tf.expand_dims(tf.reduce_sum(mask, axis=-1), axis=1)\n text_rep = tf.reduce_sum(all_h, axis=1) / den \n return text_rep\n\n def kl_divergence(self, mu, log_sigma_sq):\n \"\"\" KL divergence for two Gaussians.\n \"\"\"\n return -0.5*tf.reduce_sum(1 + log_sigma_sq - mu**2 - tf.exp(log_sigma_sq), 1) \n\ndef run_training_epoch(args, data, model, hyperparams, session, train_op=None, shuffle=False, mode='train'):\n \"\"\" Execute training epoch for Autoencoder.\n\n Args:\n args: Arguments from parser in train_grocerystore.py.\n data: Data used during epoch.\n model: Model used during epoch.\n hyperparams: Hyperparameters for training.\n session: Tensorflow session. \n train_op: Op for computing gradients and updating parameters in model.\n shuffle: For shuffling data before epoch.\n mode: Training/validation mode.\n\n Returns:\n Metrics in python dictionary.\n\n \"\"\"\n # Hyperparameters\n batch_size = hyperparams['batch_size']\n dropout_rate = hyperparams['dropout_rate']\n kl_weight = hyperparams['kl_weight']\n is_training = hyperparams['is_training']\n\n # Data\n features = data['features']\n labels = data['labels']\n captions = data['captions']\n n_classes = data['n_classes']\n\n n_examples = len(features)\n n_batches = int(np.ceil(n_examples/batch_size))\n if shuffle:\n perm = np.random.permutation(n_examples)\n features = features[perm]\n labels = labels[perm]\n \n total_loss = 0.\n x_loss = 0.\n w_loss = 0.\n kl_loss_z = 0.\n kl_loss_ux = 0.\n kl_loss_uw = 0.\n \n for i in range(n_batches):\n start = i * batch_size\n end = start + batch_size\n if end > n_examples:\n end = n_examples\n\n # Prepare batch and hyperparameters \n x_batch = features[start:end]\n feed_dict={model.x: x_batch}\n captions_batch = load_captions(captions, labels[start:end])\n feed_dict[model.captions] = captions_batch\n feed_dict[model.dropout_rate] = dropout_rate\n\n if mode == 'train':\n # Training step\n train_step_results = session.run([train_op] + model.log_var, feed_dict=feed_dict) \n total_loss += train_step_results[1]\n kl_loss_z += np.sum(train_step_results[2])\n x_loss += np.sum(train_step_results[3])\n w_loss += np.sum(train_step_results[4])\n kl_loss_ux += np.sum(train_step_results[5])\n kl_loss_uw += np.sum(train_step_results[6])\n\n elif mode == 'val':\n # Validation step\n val_step_results = session.run(model.val_log_var, feed_dict=feed_dict)\n total_loss += val_step_results[0]\n kl_loss_z += np.sum(val_step_results[1])\n x_loss += np.sum(val_step_results[2])\n w_loss += np.sum(val_step_results[3])\n kl_loss_ux += np.sum(val_step_results[4])\n kl_loss_uw += np.sum(val_step_results[5])\n\n else:\n raise ValueError(\"Argument \\'mode\\' %s doesn't exist!\" %mode)\n\n # Epoch finished, return results. clf_loss and accuracy are zero if args.classifier_head is False\n results = {'total_loss': total_loss / n_batches, 'x_loss': x_loss / n_examples, 'w_loss': w_loss / n_examples,\n 'kl_loss_z': kl_loss_z / n_examples, 'kl_loss_ux': kl_loss_ux / n_examples, 'kl_loss_uw': kl_loss_uw / n_examples,}\n return results" ]
[ [ "tensorflow.exp", "numpy.ceil", "tensorflow.shape", "tensorflow.concat", "tensorflow.nn.leaky_relu", "numpy.sum", "numpy.random.permutation", "tensorflow.variable_scope", "tensorflow.placeholder", "tensorflow.reduce_sum", "tensorflow.layers.dense", "tensorflow.reduce_mean", "tensorflow.placeholder_with_default", "tensorflow.identity" ] ]
rhett-chen/graspnet-baseline
[ "825d1885e100e418b7a11590f18957270db09408" ]
[ "pointnet2/pointnet2_utils.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates.\n# \n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n''' Modified based on: https://github.com/erikwijmans/Pointnet2_PyTorch '''\nfrom __future__ import (\n division,\n absolute_import,\n with_statement,\n print_function,\n unicode_literals,\n)\nimport torch\nfrom torch.autograd import Function\nimport torch.nn as nn\nimport pytorch_utils as pt_utils\nimport sys\nimport builtins\n# try:\n# import builtins\n# except:\n#\n# import __builtin__ as builtins\n\ntry:\n import bi_pointnet2._ext as _ext\nexcept ImportError:\n if not getattr(builtins, \"__POINTNET2_SETUP__\", False):\n raise ImportError(\n \"Could not import _ext module.\\n\"\n \"Please see the setup instructions in the README: \"\n \"https://github.com/erikwijmans/Pointnet2_PyTorch/blob/master/README.rst\"\n )\n\nif False:\n # Workaround for type hints without depending on the `typing` module\n from typing import *\n\n\nclass RandomDropout(nn.Module):\n def __init__(self, p=0.5, inplace=False):\n super(RandomDropout, self).__init__()\n self.p = p\n self.inplace = inplace\n\n def forward(self, X):\n theta = torch.Tensor(1).uniform_(0, self.p)[0]\n return pt_utils.feature_dropout_no_scaling(X, theta, self.train, self.inplace)\n\n\nclass FurthestPointSampling(Function):\n @staticmethod\n def forward(ctx, xyz, npoint):\n # type: (Any, torch.Tensor, int) -> torch.Tensor\n r\"\"\"\n Uses iterative furthest point sampling to select a set of npoint features that have the largest\n minimum distance\n\n Parameters\n ----------\n xyz : torch.Tensor\n (B, N, 3) tensor where N > npoint\n npoint : int32\n number of features in the sampled set\n\n Returns\n -------\n torch.Tensor\n (B, npoint) tensor containing the set\n \"\"\"\n return _ext.furthest_point_sampling(xyz, npoint)\n\n @staticmethod\n def backward(xyz, a=None):\n return None, None\n\n\nfurthest_point_sample = FurthestPointSampling.apply\n\n\nclass GatherOperation(Function):\n @staticmethod\n def forward(ctx, features, idx):\n # type: (Any, torch.Tensor, torch.Tensor) -> torch.Tensor\n r\"\"\"\n\n Parameters\n ----------\n features : torch.Tensor\n (B, C, N) tensor\n\n idx : torch.Tensor\n (B, npoint) tensor of the features to gather\n\n Returns\n -------\n torch.Tensor\n (B, C, npoint) tensor\n \"\"\"\n\n _, C, N = features.size()\n\n ctx.for_backwards = (idx, C, N)\n\n return _ext.gather_points(features, idx)\n\n @staticmethod\n def backward(ctx, grad_out):\n idx, C, N = ctx.for_backwards\n\n grad_features = _ext.gather_points_grad(grad_out.contiguous(), idx, N)\n return grad_features, None\n\n\ngather_operation = GatherOperation.apply\n\n\nclass ThreeNN(Function):\n @staticmethod\n def forward(ctx, unknown, known):\n # type: (Any, torch.Tensor, torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]\n r\"\"\"\n Find the three nearest neighbors of unknown in known\n Parameters\n ----------\n unknown : torch.Tensor\n (B, n, 3) tensor of known features\n known : torch.Tensor\n (B, m, 3) tensor of unknown features\n\n Returns\n -------\n dist : torch.Tensor\n (B, n, 3) l2 distance to the three nearest neighbors\n idx : torch.Tensor\n (B, n, 3) index of 3 nearest neighbors\n \"\"\"\n dist2, idx = _ext.three_nn(unknown, known)\n\n return torch.sqrt(dist2), idx\n\n @staticmethod\n def backward(ctx, a=None, b=None):\n return None, None\n\n\nthree_nn = ThreeNN.apply\n\n\nclass ThreeInterpolate(Function):\n @staticmethod\n def forward(ctx, features, idx, weight):\n # type(Any, torch.Tensor, torch.Tensor, torch.Tensor) -> Torch.Tensor\n r\"\"\"\n Performs weight linear interpolation on 3 features\n Parameters\n ----------\n features : torch.Tensor\n (B, c, m) Features descriptors to be interpolated from\n idx : torch.Tensor\n (B, n, 3) three nearest neighbors of the target features in features\n weight : torch.Tensor\n (B, n, 3) weights\n\n Returns\n -------\n torch.Tensor\n (B, c, n) tensor of the interpolated features\n \"\"\"\n B, c, m = features.size()\n n = idx.size(1)\n\n ctx.three_interpolate_for_backward = (idx, weight, m)\n\n return _ext.three_interpolate(features, idx, weight)\n\n @staticmethod\n def backward(ctx, grad_out):\n # type: (Any, torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]\n r\"\"\"\n Parameters\n ----------\n grad_out : torch.Tensor\n (B, c, n) tensor with gradients of ouputs\n\n Returns\n -------\n grad_features : torch.Tensor\n (B, c, m) tensor with gradients of features\n\n None\n\n None\n \"\"\"\n idx, weight, m = ctx.three_interpolate_for_backward\n\n grad_features = _ext.three_interpolate_grad(\n grad_out.contiguous(), idx, weight, m\n )\n\n return grad_features, None, None\n\n\nthree_interpolate = ThreeInterpolate.apply\n\n\nclass GroupingOperation(Function):\n @staticmethod\n def forward(ctx, features, idx):\n # type: (Any, torch.Tensor, torch.Tensor) -> torch.Tensor\n r\"\"\"\n\n Parameters\n ----------\n features : torch.Tensor\n (B, C, N) tensor of features to group\n idx : torch.Tensor\n (B, npoint, nsample) tensor containing the indicies of features to group with\n\n Returns\n -------\n torch.Tensor\n (B, C, npoint, nsample) tensor\n \"\"\"\n B, nfeatures, nsample = idx.size()\n _, C, N = features.size()\n\n ctx.for_backwards = (idx, N)\n\n return _ext.group_points(features, idx)\n\n @staticmethod\n def backward(ctx, grad_out):\n # type: (Any, torch.tensor) -> Tuple[torch.Tensor, torch.Tensor]\n r\"\"\"\n\n Parameters\n ----------\n grad_out : torch.Tensor\n (B, C, npoint, nsample) tensor of the gradients of the output from forward\n\n Returns\n -------\n torch.Tensor\n (B, C, N) gradient of the features\n None\n \"\"\"\n idx, N = ctx.for_backwards\n\n grad_features = _ext.group_points_grad(grad_out.contiguous(), idx, N)\n\n return grad_features, None\n\n\ngrouping_operation = GroupingOperation.apply\n\n\nclass BallQuery(Function):\n @staticmethod\n def forward(ctx, radius, nsample, xyz, new_xyz):\n # type: (Any, float, int, torch.Tensor, torch.Tensor) -> torch.Tensor\n r\"\"\"\n\n Parameters\n ----------\n radius : float\n radius of the balls\n nsample : int\n maximum number of features in the balls\n xyz : torch.Tensor\n (B, N, 3) xyz coordinates of the features\n new_xyz : torch.Tensor\n (B, npoint, 3) centers of the ball query\n\n Returns\n -------\n torch.Tensor\n (B, npoint, nsample) tensor with the indicies of the features that form the query balls\n \"\"\"\n return _ext.ball_query(new_xyz, xyz, radius, nsample)\n\n @staticmethod\n def backward(ctx, a=None):\n return None, None, None, None\n\n\nball_query = BallQuery.apply\n\n\nclass QueryAndGroup(nn.Module):\n r\"\"\"\n Groups with a ball query of radius\n\n Parameters\n ---------\n radius : float32\n Radius of ball\n nsample : int32\n Maximum number of features to gather in the ball\n \"\"\"\n\n def __init__(self, radius, nsample, use_xyz=True, ret_grouped_xyz=False, normalize_xyz=False, sample_uniformly=False, ret_unique_cnt=False):\n # type: (QueryAndGroup, float, int, bool) -> None\n super(QueryAndGroup, self).__init__()\n self.radius, self.nsample, self.use_xyz = radius, nsample, use_xyz\n self.ret_grouped_xyz = ret_grouped_xyz\n self.normalize_xyz = normalize_xyz\n self.sample_uniformly = sample_uniformly\n self.ret_unique_cnt = ret_unique_cnt\n if self.ret_unique_cnt:\n assert(self.sample_uniformly)\n\n def forward(self, xyz, new_xyz, features=None):\n # type: (QueryAndGroup, torch.Tensor. torch.Tensor, torch.Tensor) -> Tuple[Torch.Tensor]\n r\"\"\"\n Parameters\n ----------\n xyz : torch.Tensor\n xyz coordinates of the features (B, N, 3)\n new_xyz : torch.Tensor\n centriods (B, npoint, 3)\n features : torch.Tensor\n Descriptors of the features (B, C, N)\n\n Returns\n -------\n new_features : torch.Tensor\n (B, 3 + C, npoint, nsample) tensor\n \"\"\"\n idx = ball_query(self.radius, self.nsample, xyz, new_xyz)\n\n if self.sample_uniformly:\n unique_cnt = torch.zeros((idx.shape[0], idx.shape[1]))\n for i_batch in range(idx.shape[0]):\n for i_region in range(idx.shape[1]):\n unique_ind = torch.unique(idx[i_batch, i_region, :])\n num_unique = unique_ind.shape[0]\n unique_cnt[i_batch, i_region] = num_unique\n sample_ind = torch.randint(0, num_unique, (self.nsample - num_unique,), dtype=torch.long)\n all_ind = torch.cat((unique_ind, unique_ind[sample_ind]))\n idx[i_batch, i_region, :] = all_ind\n\n\n xyz_trans = xyz.transpose(1, 2).contiguous()\n grouped_xyz = grouping_operation(xyz_trans, idx) # (B, 3, npoint, nsample)\n grouped_xyz -= new_xyz.transpose(1, 2).unsqueeze(-1)\n if self.normalize_xyz:\n grouped_xyz /= self.radius\n\n if features is not None:\n grouped_features = grouping_operation(features, idx)\n if self.use_xyz:\n new_features = torch.cat(\n [grouped_xyz, grouped_features], dim=1\n ) # (B, C + 3, npoint, nsample)\n else:\n new_features = grouped_features\n else:\n assert (\n self.use_xyz\n ), \"Cannot have not features and not use xyz as a feature!\"\n new_features = grouped_xyz\n\n ret = [new_features]\n if self.ret_grouped_xyz:\n ret.append(grouped_xyz)\n if self.ret_unique_cnt:\n ret.append(unique_cnt)\n if len(ret) == 1:\n return ret[0]\n else:\n return tuple(ret)\n\n\nclass GroupAll(nn.Module):\n r\"\"\"\n Groups all features\n\n Parameters\n ---------\n \"\"\"\n\n def __init__(self, use_xyz=True, ret_grouped_xyz=False):\n # type: (GroupAll, bool) -> None\n super(GroupAll, self).__init__()\n self.use_xyz = use_xyz\n\n def forward(self, xyz, new_xyz, features=None):\n # type: (GroupAll, torch.Tensor, torch.Tensor, torch.Tensor) -> Tuple[torch.Tensor]\n r\"\"\"\n Parameters\n ----------\n xyz : torch.Tensor\n xyz coordinates of the features (B, N, 3)\n new_xyz : torch.Tensor\n Ignored\n features : torch.Tensor\n Descriptors of the features (B, C, N)\n\n Returns\n -------\n new_features : torch.Tensor\n (B, C + 3, 1, N) tensor\n \"\"\"\n\n grouped_xyz = xyz.transpose(1, 2).unsqueeze(2)\n if features is not None:\n grouped_features = features.unsqueeze(2)\n if self.use_xyz:\n new_features = torch.cat(\n [grouped_xyz, grouped_features], dim=1\n ) # (B, 3 + C, 1, N)\n else:\n new_features = grouped_features\n else:\n new_features = grouped_xyz\n\n if self.ret_grouped_xyz:\n return new_features, grouped_xyz\n else:\n return new_features\n\n\nclass CylinderQuery(Function):\n @staticmethod\n def forward(ctx, radius, hmin, hmax, nsample, xyz, new_xyz, rot):\n # type: (Any, float, float, float, int, torch.Tensor, torch.Tensor, torch.Tensor) -> torch.Tensor\n r\"\"\"\n\n Parameters\n ----------\n radius : float\n radius of the cylinders\n hmin, hmax : float\n endpoints of cylinder height in x-rotation axis\n nsample : int\n maximum number of features in the cylinders\n xyz : torch.Tensor\n (B, N, 3) xyz coordinates of the features\n new_xyz : torch.Tensor\n (B, npoint, 3) centers of the cylinder query\n rot: torch.Tensor\n (B, npoint, 9) flatten rotation matrices from\n cylinder frame to world frame\n\n Returns\n -------\n torch.Tensor\n (B, npoint, nsample) tensor with the indicies of the features that form the query balls\n \"\"\"\n return _ext.cylinder_query(new_xyz, xyz, rot, radius, hmin, hmax, nsample)\n\n @staticmethod\n def backward(ctx, a=None):\n return None, None, None, None, None, None, None\n\n\ncylinder_query = CylinderQuery.apply\n\n\nclass CylinderQueryAndGroup(nn.Module):\n r\"\"\"\n Groups with a cylinder query of radius and height\n\n Parameters\n ---------\n radius : float32\n Radius of cylinder\n hmin, hmax: float32\n endpoints of cylinder height in x-rotation axis\n nsample : int32\n Maximum number of features to gather in the ball\n \"\"\"\n\n def __init__(self, radius, hmin, hmax, nsample, use_xyz=True, ret_grouped_xyz=False, normalize_xyz=False, rotate_xyz=True, sample_uniformly=False, ret_unique_cnt=False):\n # type: (CylinderQueryAndGroup, float, float, float, int, bool) -> None\n super(CylinderQueryAndGroup, self).__init__()\n self.radius, self.nsample, self.hmin, self.hmax, = radius, nsample, hmin, hmax\n self.use_xyz = use_xyz\n self.ret_grouped_xyz = ret_grouped_xyz\n self.normalize_xyz = normalize_xyz\n self.rotate_xyz = rotate_xyz\n self.sample_uniformly = sample_uniformly\n self.ret_unique_cnt = ret_unique_cnt\n if self.ret_unique_cnt:\n assert(self.sample_uniformly)\n\n def forward(self, xyz, new_xyz, rot, features=None):\n # type: (QueryAndGroup, torch.Tensor. torch.Tensor, torch.Tensor) -> Tuple[Torch.Tensor]\n r\"\"\"\n Parameters\n ----------\n xyz : torch.Tensor\n xyz coordinates of the features (B, N, 3)\n new_xyz : torch.Tensor\n centriods (B, npoint, 3)\n rot : torch.Tensor\n rotation matrices (B, npoint, 3, 3)\n features : torch.Tensor\n Descriptors of the features (B, C, N)\n\n Returns\n -------\n new_features : torch.Tensor\n (B, 3 + C, npoint, nsample) tensor\n \"\"\"\n B, npoint, _ = new_xyz.size()\n idx = cylinder_query(self.radius, self.hmin, self.hmax, self.nsample, xyz, new_xyz, rot.view(B, npoint, 9))\n\n if self.sample_uniformly:\n unique_cnt = torch.zeros((idx.shape[0], idx.shape[1]))\n for i_batch in range(idx.shape[0]):\n for i_region in range(idx.shape[1]):\n unique_ind = torch.unique(idx[i_batch, i_region, :])\n num_unique = unique_ind.shape[0]\n unique_cnt[i_batch, i_region] = num_unique\n sample_ind = torch.randint(0, num_unique, (self.nsample - num_unique,), dtype=torch.long)\n all_ind = torch.cat((unique_ind, unique_ind[sample_ind]))\n idx[i_batch, i_region, :] = all_ind\n\n\n xyz_trans = xyz.transpose(1, 2).contiguous()\n grouped_xyz = grouping_operation(xyz_trans, idx) # (B, 3, npoint, nsample)\n grouped_xyz -= new_xyz.transpose(1, 2).unsqueeze(-1)\n if self.normalize_xyz:\n grouped_xyz /= self.radius\n if self.rotate_xyz:\n grouped_xyz_ = grouped_xyz.permute(0, 2, 3, 1).contiguous() # (B, npoint, nsample, 3)\n grouped_xyz_ = torch.matmul(grouped_xyz_, rot)\n grouped_xyz = grouped_xyz_.permute(0, 3, 1, 2).contiguous()\n\n\n if features is not None:\n grouped_features = grouping_operation(features, idx)\n if self.use_xyz:\n new_features = torch.cat(\n [grouped_xyz, grouped_features], dim=1\n ) # (B, C + 3, npoint, nsample)\n else:\n new_features = grouped_features\n else:\n assert (\n self.use_xyz\n ), \"Cannot have not features and not use xyz as a feature!\"\n new_features = grouped_xyz\n\n ret = [new_features]\n if self.ret_grouped_xyz:\n ret.append(grouped_xyz)\n if self.ret_unique_cnt:\n ret.append(unique_cnt)\n if len(ret) == 1:\n return ret[0]\n else:\n return tuple(ret)" ]
[ [ "torch.zeros", "torch.cat", "torch.sqrt", "torch.unique", "torch.randint", "torch.Tensor", "torch.matmul" ] ]
jkelowitt/GenStrIde
[ "7047ac6bc4943030cf3ec21abf01dac8ed713d47" ]
[ "utils/DataContainer.py" ]
[ "import numpy as np\nimport random\nimport sys\n\nclass data_t(object):\n def __init__(self, data, labels=None):\n self.labels = labels\n self.data = data\n self.num_examples = data.shape[0]\n\n def next_batch(self, batch_size, index):\n idx = index * batch_size\n n_idx = index * batch_size + batch_size\n return self.data[idx:n_idx, :], self.labels[idx:n_idx, :]\n\n# expects a numpy array of data and a corresponding numpy array of labels\n# samples on the rows, features on the columns\nclass DataContainer:\n def __init__(self, data, labels, train_split=0.8, test_split=0.2):\n assert(data.shape[0] == labels.shape[0])\n self.num_classes = labels.shape[1]\n self.class_counts = {}\n self.train, self.test = self.partition(data, labels, train_split, test_split)\n\n # Shuffle training dataset (when creating dataset)\n def shuffle_and_transform(self, data, labels):\n stacked_d = np.vstack(data)\n stacked_l = np.vstack(labels)\n\n samples = random.sample(range(stacked_d.shape[0]),stacked_d.shape[0])\n\n # convert lists to numpy arrays\n stacked_d = stacked_d[samples]\n stacked_l = stacked_l[samples]\n\n return data_t(stacked_d, stacked_l)\n\n # Shuffle training dataset (in between epochs)\n def shuffle(self):\n idxs = np.arange(self.train.data.shape[0])\n np.random.shuffle(idxs)\n self.train.data = np.squeeze(self.train.data[idxs])\n self.train.labels = np.squeeze(self.train.labels[idxs])\n\n def partition(self, data, labels, train_split=0.8, test_split=0.2):\n x_train = []\n y_train = []\n x_test = []\n y_test = []\n\n for i in range(self.num_classes):\n # find where the labels are equal to the certain class\n idxs = np.where(np.argmax(labels, axis=1) == i)[0]\n np.random.shuffle(idxs)\n\n # record the class count information\n self.class_counts[str(i)] = idxs.shape[0]\n\n # get the int that splits the train/test sets\n split = int(train_split * idxs.shape[0])\n\n # append class data to respective lists\n x_train.append(data[idxs[:split]])\n y_train.append(labels[idxs[:split]])\n\n x_test.append(data[idxs[split:]])\n y_test.append(labels[idxs[split:]])\n\n # format into datacontainer \n train = self.shuffle_and_transform(x_train, y_train)\n test = self.shuffle_and_transform(x_test, y_test)\n\n return [train, test]\n\n" ]
[ [ "numpy.random.shuffle", "numpy.argmax", "numpy.arange", "numpy.squeeze", "numpy.vstack" ] ]
yukiito2/cupy
[ "7e707b8ccea13d79b9026c91c27143cb78014d4b" ]
[ "tests/cupy_tests/logic_tests/test_type_test.py" ]
[ "import numpy\n\nfrom cupy import testing\n\n\nclass TestBinaryRepr(testing.NumpyAliasBasicTestBase):\n\n func = 'isscalar'\n\n\[email protected](\n *testing.product({\n 'value': [\n 0, 0.0, True,\n numpy.int32(1), numpy.array([1, 2], numpy.int32),\n numpy.complex(1), numpy.complex(1j), numpy.complex(1 + 1j),\n None, object(), 'abc', '', int, numpy.int32]}))\nclass TestBinaryReprValues(testing.NumpyAliasValuesTestBase):\n\n func = 'isscalar'\n\n def setUp(self):\n self.args = (self.value,)\n" ]
[ [ "numpy.int32", "numpy.array", "numpy.complex" ] ]
dolphindb/api_python3
[ "caf1c6a38fe3dc0febf33ca5f299c2cdae0f139d" ]
[ "test/test_upload.py" ]
[ "import unittest\r\nimport dolphindb as ddb\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom numpy.testing import assert_array_equal\r\nfrom pandas.testing import assert_frame_equal, assert_series_equal\r\nfrom setup import HOST, PORT, WORK_DIR, DATA_DIR\r\n\r\n\r\nclass TestUploadObject(unittest.TestCase):\r\n @classmethod\r\n def setUp(cls):\r\n cls.s = ddb.session()\r\n cls.s.connect(HOST, PORT, \"admin\", \"123456\")\r\n\r\n @classmethod\r\n def tearDownClass(cls):\r\n pass\r\n\r\n def test_upload_int_scalar(self):\r\n a = 1\r\n self.s.upload({\"a\": a})\r\n self.assertEqual(self.s.run(\"eqObj(a, 1)\"), True)\r\n re = self.s.run(\"a\")\r\n self.assertEqual(re, 1)\r\n\r\n def test_upload_bool_scalar(self):\r\n a = True\r\n self.s.upload({\"a\": a})\r\n self.assertEqual(self.s.run(\"eqObj(a, true)\"), True)\r\n re = self.s.run(\"a\")\r\n self.assertEqual(re, True)\r\n\r\n def test_upload_float_scalar(self):\r\n a = 5.5\r\n self.s.upload({\"a\": a})\r\n self.assertEqual(self.s.run(\"eqObj(a, 5.5, 1)\"), True)\r\n re = self.s.run(\"a\")\r\n self.assertEqual(re, 5.5)\r\n\r\n def test_upload_complex_scalar(self):\r\n pass\r\n\r\n def test_upload_string_scalar(self):\r\n a = 'Runoob'\r\n self.s.upload({'a': a})\r\n self.assertEqual(self.s.run(\"eqObj(a, 'Runoob')\"), True)\r\n re = self.s.run(\"a\")\r\n self.assertEqual(re, 'Runoob')\r\n\r\n def test_upload_mix_list(self):\r\n list = ['abcd', 786, 2.23, 'runoob', 70.2]\r\n self.s.upload({'list': list})\r\n self.assertEqual(self.s.run(\"eqObj(list, ['abcd', 786, 2.23, 'runoob', 70.2])\"), True)\r\n re = self.s.run(\"list\")\r\n self.assertEqual((re == list).all(), True)\r\n\r\n def test_upload_int_list(self):\r\n a = [4, 5, 7, -3]\r\n self.s.upload({\"a\": a})\r\n self.assertEqual(self.s.run(\"eqObj(a, [4, 5, 7, -3])\"), True)\r\n re = self.s.run(\"a\")\r\n self.assertEqual((re == a).all(), True)\r\n \r\n def test_upload_string_list(self):\r\n a = ['aaa', 'bbb', 'ccc']\r\n self.s.upload({\"a\": a})\r\n self.assertEqual(self.s.run(\"eqObj(a, ['aaa', 'bbb', 'ccc'])\"), True)\r\n re = self.s.run(\"a\")\r\n self.assertEqual((re == a).all(), True)\r\n\r\n def test_upload_bool_list(self):\r\n a = [True, False, False, True]\r\n self.s.upload({\"a\": a})\r\n self.assertEqual(self.s.run(\"eqObj(a, [true, false, false, true])\"), True)\r\n re = self.s.run(\"a\")\r\n self.assertEqual((re == a).all(), True)\r\n\r\n def test_upload_list_list(self):\r\n a = [[1, 2, 3], [4, 5, 6]]\r\n self.s.upload({\"a\": a})\r\n self.assertEqual(self.s.run(\"eqObj(a[0], [1, 2, 3])\"), True)\r\n self.assertEqual(self.s.run(\"eqObj(a[1], [4, 5, 6])\"), True)\r\n re = self.s.run(\"a\")\r\n assert_array_equal(re, [[1, 2, 3], [4, 5, 6]])\r\n \r\n def test_upload_tuple(self):\r\n tuple = ('abcd', 786 , 2.23, 'runoob', 70.2)\r\n self.s.upload({\"tuple\": tuple})\r\n self.assertEqual(self.s.run(\"eqObj(tuple, ['abcd', 786, 2.23, 'runoob', 70.2])\"), True)\r\n re = self.s.run(\"tuple\")\r\n self.assertEqual((re==tuple).all(), True)\r\n\r\n def test_upload_set(self):\r\n a = set('abracadabra')\r\n self.s.upload({'a': a})\r\n self.assertEqual(self.s.run(\"eqObj(sort(a.keys()), `a`b`c`d`r)\"), True)\r\n re = self.s.run(\"a\")\r\n self.assertSetEqual(re, a)\r\n\r\n def test_upload_pandas_series_without_index(self):\r\n a = pd.Series([4, 7, -5, 3])\r\n self.s.upload({\"a\": a})\r\n self.assertEqual(self.s.run(\"eqObj(a, [4,7,-5,3])\"), True)\r\n re = self.s.run(\"a\")\r\n assert_array_equal(re, [4, 7, -5, 3])\r\n\r\n def test_upload_pandas_series_dtype_object(self):\r\n a = pd.Series(['a', 'b', 'c', 'd'], dtype = \"object\")\r\n self.s.upload({\"a\": a})\r\n self.assertEqual(self.s.run(\"eqObj(a, `a`b`c`d)\"), True)\r\n re = self.s.run(\"a\")\r\n assert_array_equal(re, ['a', 'b', 'c', 'd'])\r\n\r\n def test_upload_pandas_series_dtype_int32(self):\r\n a = pd.Series([1, 2, 3], dtype=\"int32\")\r\n self.s.upload({\"a\": a})\r\n self.assertEqual(self.s.run(\"eqObj(a, [1, 2, 3])\"), True)\r\n re = self.s.run(\"a\")\r\n assert_array_equal(re, [1, 2, 3])\r\n \r\n def test_upload_pandas_series_dtype_int64(self):\r\n a = pd.Series([1, 2, 3], dtype=\"int64\")\r\n self.s.upload({\"a\": a})\r\n self.assertEqual(self.s.run(\"eqObj(a, [1, 2, 3])\"), True)\r\n re = self.s.run(\"a\")\r\n assert_array_equal(re, [1, 2, 3])\r\n\r\n def test_upload_pandas_series_dtype_float32(self):\r\n a = pd.Series([1, 2, np.nan], dtype=\"float32\")\r\n self.s.upload({\"a\": a})\r\n self.assertEqual(self.s.run(\"eqObj(a, [1.0, 2.0, NULL])\"), True)\r\n re = self.s.run(\"a\")\r\n assert_array_equal(re, [1, 2, np.nan])\r\n\r\n def test_upload_pandas_series_dtype_float64(self):\r\n a = pd.Series([1, 2, np.nan], dtype=\"float64\")\r\n self.s.upload({\"a\": a})\r\n self.assertEqual(self.s.run(\"eqObj(a, [1.0, 2.0, NULL])\"), True)\r\n re = self.s.run(\"a\")\r\n assert_array_equal(re, [1, 2, np.nan])\r\n\r\n def test_upload_pandas_series_dtype_datetime64(self):\r\n a = pd.Series(['2018-07-01', '2019-07-01', '2019-10-01'], dtype=\"datetime64[ns]\")\r\n self.s.upload({\"a\": a})\r\n self.assertEqual(self.s.run(\"eqObj(a, [2018.07.01T00:00:00.000000000, 2019.07.01T00:00:00.000000000, 2019.10.01T00:00:00.000000000])\"), True)\r\n re = self.s.run(\"a\")\r\n assert_array_equal(re, np.array(['2018-07-01T00:00:00.000000000','2019-07-01T00:00:00.000000000','2019-10-01T00:00:00.000000000'], dtype=\"datetime64[ns]\"))\r\n\r\n def test_upload_pandas_series_with_index(self):\r\n a = pd.Series([4, 7, -5, 3], index=['a', 'b', 'c', 'd'])\r\n self.s.upload({\"a\": a})\r\n self.assertEqual(self.s.run(\"eqObj(a, [4,7,-5,3])\"), True)\r\n re = self.s.run(\"a\")\r\n assert_array_equal(re, [4, 7, -5, 3]) # index aborted\r\n\r\n def test_upload_nan(self):\r\n a = np.nan\r\n self.s.upload({\"a\": a})\r\n self.assertEqual(self.s.run(\"eqObj(a, int())\"), True)\r\n re = self.s.run(\"a\")\r\n self.assertEqual(pd.isnull(re), True)\r\n\r\n def test_upload_array_with_nan(self):\r\n a = [np.nan, 1, 2, 3]\r\n self.s.upload({'a': a})\r\n self.assertEqual(self.s.run(\"eqObj(a, [,1,2,3])\"), True)\r\n re = self.s.run(\"a\")\r\n assert_array_equal(re, [np.nan, 1, 2, 3])\r\n\r\n def test_upload_dataframe(self):\r\n data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],\r\n 'year': [2000, 2001, 2002, 2001, 2002],\r\n 'pop': [1.5, 1.7, 3.6, 2.4, 2.9]}\r\n df = pd.DataFrame(data)\r\n self.s.upload({\"t1\": df})\r\n self.assertEqual(self.s.run(\"all(each(eqObj,t1.values(),\"\r\n \"table(['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'] as state, \"\r\n \"[2000, 2001, 2002, 2001, 2002] as year, \"\r\n \"[1.5, 1.7, 3.6, 2.4, 2.9] as pop).values()))\"), True)\r\n re = self.s.run(\"t1\")\r\n assert_frame_equal(re, df)\r\n\r\n def test_upload_dict(self):\r\n data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],\r\n 'year': [2000, 2001, 2002, 2001, 2002],\r\n 'pop': [5, 7, 6, 4, 9]}\r\n self.s.upload({\"d\": data})\r\n self.assertEqual(self.s.run(\"eqObj(d[`state].sort(), `Nevada`Nevada`Ohio`Ohio`Ohio)\"), True)\r\n self.assertEqual(self.s.run(\"eqObj(d[`year].sort(), [2000, 2001, 2001, 2002, 2002])\"), True)\r\n self.assertEqual(self.s.run(\"eqObj(d[`pop].sort(), [4, 5, 6, 7, 9])\"), True)\r\n re = self.s.run(\"d\")\r\n self.assertEqual((data['state'] == re['state']).all(), True)\r\n self.assertEqual((data['year'] == re['year']).all(), True)\r\n self.assertEqual((data['pop'] == re['pop']).all(), True)\r\n\r\n def test_upload_numpy_one_dimension_array(self):\r\n a = np.array(range(10))\r\n self.s.upload({\"a\": a})\r\n self.assertEqual(self.s.run(\"eqObj(a, 0..9)\"), True)\r\n re =self.s.run(\"a\")\r\n assert_array_equal(re, [0,1,2,3,4,5,6,7,8,9])\r\n\r\n def test_upload_numpy_two_dimension_array(self):\r\n a = np.array([[1, 2, 3], [4, 5, 6]])\r\n self.s.upload({\"a\": a})\r\n self.assertEqual(self.s.run(\"eqObj(a, 1 4 2 5 3 6$2:3)\"), True)\r\n re = self.s.run(\"a\")\r\n # TODO:BUG\r\n # assert_array_equal(re, a)\r\n assert_array_equal(re[0], a)\r\n\r\n def test_upload_matrix(self):\r\n a = self.s.run(\"cross(+, 1..5, 1..5)\")\r\n b = self.s.run(\"1..25$5:5\")\r\n self.s.upload({'a': a[0], 'b': b[0]})\r\n self.assertEqual(self.s.run(\"eqObj(a, cross(+, 1..5, 1..5))\"), True)\r\n self.assertEqual(self.s.run(\"eqObj(b, 1..25$5:5)\"), True)\r\n\r\n re = self.s.run('a+b')\r\n self.assertEqual((re[0][0] == [3, 9, 15, 21, 27]).all(), True)\r\n self.assertEqual((re[0][1] == [5, 11, 17, 23, 29]).all(), True)\r\n self.assertEqual((re[0][2] == [7, 13, 19, 25, 31]).all(), True)\r\n self.assertEqual((re[0][3] == [9, 15, 21, 27, 33]).all(), True)\r\n self.assertEqual((re[0][4] == [11, 17, 23, 29, 35]).all(), True)\r\n\r\n def test_upload_numpy_eye_matrix(self):\r\n a = np.eye(4)\r\n self.s.upload({\"a\": a})\r\n self.assertEqual(self.s.run(\"eqObj(a, [1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]*1.0$4:4)\"), True)\r\n re = self.s.run(\"a\")\r\n assert_array_equal(re[0], [[1., 0., 0., 0.],[0., 1., 0., 0.],[0., 0., 1., 0.],[0., 0., 0., 1.]])\r\n\r\n def test_upload_numpy_matrix(self):\r\n a = np.matrix('1 2; 3 4')\r\n self.s.upload({\"a\": a})\r\n self.assertEqual(self.s.run(\"eqObj(a, [1,3,2,4]$2:2)\"), True)\r\n re = self.s.run(\"a\")\r\n assert_array_equal(re[0], [[1, 2],[3, 4]])\r\n \r\n def test_upload_float32_dataframe(self):\r\n pdf = pd.DataFrame({'tfloat': np.arange(1, 10, 1, dtype='float32')})\r\n pdf.loc[1,:]=np.nan\r\n self.s.upload({'t':pdf})\r\n re=self.s.run(\"t\")\r\n assert_frame_equal(pdf, re, check_dtype=False)\r\n\r\n def test_upload_numpy_scalar_dtype_datetime64_day(self):\r\n a = np.datetime64('2012-06-08', 'D')\r\n self.s.upload({'a': a})\r\n self.assertTrue(self.s.run(\"eqObj(a, 2012.06.08)\"))\r\n re = self.s.run('a')\r\n self.assertEqual(a, re)\r\n # TODO:\r\n # a = np.datetime64('NaT', 'D')\r\n # self.s.upload({'a': a})\r\n # self.assertTrue(self.s.run(\"eqObj(a, date())\"))\r\n # re = self.s.run('a')\r\n # self.assertEqual(a, re)\r\n\r\n def test_upload_numpy_scalar_dtype_datetime64_month(self):\r\n a = np.datetime64('2012-06', 'M')\r\n self.s.upload({'a': a})\r\n self.assertTrue(self.s.run(\"eqObj(a, 2012.06M)\"))\r\n re = self.s.run('a')\r\n self.assertEqual(a, re)\r\n # TODO:\r\n # a = np.datetime64('NaT', 'M')\r\n # self.s.upload({'a': a})\r\n # self.assertTrue(self.s.run(\"eqObj(a, month())\"))\r\n # re = self.s.run('a')\r\n # self.assertEqual(a, re)\r\n\r\n def test_upload_numpy_scalar_dtype_year(self):\r\n pass\r\n # a = np.datetime64('2012', 'Y')\r\n # self.s.upload({'a': a})\r\n\r\n def test_upload_numpy_scalar_dtype_datetime64_minute(self):\r\n a = np.datetime64('2005-02-25T03:30', 'm')\r\n self.s.upload({'a': a})\r\n re = self.s.run('a')\r\n self.assertEqual(a, re)\r\n # TODO:\r\n # a = np.datetime64('NaT', 'm')\r\n # self.s.upload({'a': a})\r\n # re = self.s.run('a')\r\n # self.assertEqual(a, re)\r\n\r\n def test_upload_numpy_scalar_dtype_datetime64_second(self):\r\n a = np.datetime64('2005-02-25T03:30:25', 's')\r\n self.s.upload({'a': a})\r\n self.assertTrue(self.s.run(\"eqObj(a, 2005.02.25T03:30:25)\"))\r\n re = self.s.run('a')\r\n self.assertEqual(a, re)\r\n # TODO:\r\n # a = np.datetime64('NaT', 's')\r\n # self.s.upload({'a': a})\r\n # re = self.s.run('a')\r\n # self.assertEqual(a, re)\r\n\r\n def test_upload_numpy_scalar_dtype_datetime64_millisecond(self):\r\n a = np.datetime64('2005-02-25T03:30:25.008', 'ms')\r\n self.s.upload({'a': a})\r\n # self.assertTrue(self.s.run(\"eqObj(a, 2005.02.05T03:30:25.008)\"))\r\n re = self.s.run('a')\r\n self.assertEqual(re, a)\r\n # TODO:\r\n # a = np.datetime64('NaT', 'ms')\r\n # self.s.upload({'a': a})\r\n # self.assertTrue(self.s.run(\"eqObj(a, timestamp())\"))\r\n # re = self.s.run('a')\r\n # self.assertEqual(a, re)\r\n \r\n def test_upload_numpy_scalar_dtype_datetime64_nanosecond(self):\r\n a = np.datetime64('2005-02-25T03:30:25.008007006', 'ns')\r\n self.s.upload({'a': a})\r\n self.assertTrue(self.s.run(\"eqObj(a, 2005.02.25T03:30:25.008007006)\"))\r\n re = self.s.run('a')\r\n self.assertEqual(re, a)\r\n # TODO:\r\n # a = np.datetime64('NaT', 'ns')\r\n # self.s.upload({'a': a})\r\n # self.assertTrue(self.s.run(\"eqObj(a, nanotimestamp())\"))\r\n # re = self.s.run('a')\r\n # self.assertEqual(a, re)\r\n\r\n\r\n def test_upload_numpy_array_dtype_datetime64_D(self):\r\n a = np.array(['2012-06-12', '1968-12-05', '2003-09-28'], dtype='datetime64[D]')\r\n self.s.upload({'aa': a})\r\n self.assertTrue(self.s.run(\"eqObj(aa, [2012.06.12, 1968.12.05, 2003.09.28])\"))\r\n re = self.s.run(\"aa\")\r\n assert_array_equal(a, re)\r\n \r\n def test_upload_dataframe_np_datetime64(self):\r\n df = pd.DataFrame({'col1': np.array(['2012-06', '2012-07', '', '2024-12'], dtype = 'datetime64[M]'),\r\n 'col2': np.array(['2012-06-01', '', '2012-07-05', '2013-09-08'], dtype = 'datetime64[D]'),\r\n 'col3': np.array(['2012-06-01T12:30:00', '2012-06-01T12:30:01', '', ''], dtype = 'datetime64'),\r\n 'col4': np.array(['2012-06-08T12:30:00.000','','','2012-06-08T12:30:00.001'], dtype='datetime64'),\r\n 'col5': np.array(['2012-06-08T12:30:00.000001', '', '2012-06-08T12:30:00.000002', ''], dtype = 'datetime64')})\r\n self.s.upload({'t': df})\r\n script = '''\r\n expected = table(nanotimestamp([2012.06.01, 2012.07.01, NULL, 2024.12.01]) as col1, nanotimestamp([2012.06.01, NULL, 2012.07.05, 2013.09.08]) as col2, nanotimestamp([2012.06.01T12:30:00, 2012.06.01T12:30:01, NULL, NULL]) as col3, nanotimestamp([2012.06.08T12:30:00.000, NULL, NULL, 2012.06.08T12:30:00.001]) as col4, [2012.06.08T12:30:00.000001000, NULL, 2012.06.08T12:30:00.000002000, NULL] as col5)\r\n loop(eqObj, expected.values(), t.values())\r\n '''\r\n re = self.s.run(script)\r\n assert_array_equal(re, [True, True, True, True, True])\r\n\r\n def test_upload_dataframe_chinese_column_name(self):\r\n df = pd.DataFrame({'编号':[1, 2, 3, 4, 5], '序号':['壹','贰','叁','肆','伍']})\r\n self.s.upload({'t': df})\r\n re = self.s.run(\"select * from t\")\r\n assert_array_equal(re['编号'], [1, 2, 3, 4, 5])\r\n assert_array_equal(re['序号'], ['壹','贰','叁','肆','伍'])\r\n\r\n def test_upload_dataframe_chinese_column_name(self):\r\n df = pd.DataFrame({'编号':[1, 2, 3, 4, 5], '序号':['壹','贰','叁','肆','伍']})\r\n self.s.upload({'t': df})\r\n re = self.s.run(\"select * from t\")\r\n assert_array_equal(re['编号'], [1, 2, 3, 4, 5])\r\n assert_array_equal(re['序号'], ['壹','贰','叁','肆','伍'])\r\n\r\n def test_upload_numpy_scalar_dtype_datetime64_h(self):\r\n a =np.datetime64(\"2020-01-01T01\",'h')\r\n self.s.upload({'a': a})\r\n self.assertTrue(self.s.run(\"eqObj(a, datehour(2020.01.01T01:00:00))\"))\r\n re = self.s.run('a')\r\n self.assertEqual(a, re)\r\n # a = np.datetime64('NaT', 'h')\r\n # self.s.upload({'a': a})\r\n # self.assertTrue(self.s.run(\"eqObj(a, datehour())\"))\r\n # re = self.s.run('a')\r\n # self.assertEqual(a, re)\r\n\r\n def test_upload_numpy_array_dtype_datetime64_h(self):\r\n a = np.array(['2012-06-12T01', '1968-12-05T01', '2003-09-28T01'], dtype='datetime64[h]')\r\n self.s.upload({'a': a})\r\n self.assertTrue(self.s.run(\"eqObj(a, datehour([2012.06.12T01:00:00,1968.12.05T01:00:00,2003.09.28T01:00:00]))\"))\r\n re = self.s.run('a')\r\n assert_array_equal(a, re)\r\n b = np.repeat(np.datetime64(\"2020-01-01T01\",'h'),500000)\r\n self.s.upload({'b': b})\r\n self.assertTrue(self.s.run(\"eqObj(b, take(datehour(2020.01.01T01:00:00),500000))\"))\r\n re = self.s.run('b')\r\n assert_array_equal(b, re)\r\n c = np.repeat(np.datetime64(\"Nat\",'h'),500000)\r\n self.s.upload({'c': c})\r\n self.assertTrue(self.s.run(\"eqObj(c, take(datehour(),500000))\"))\r\n re = self.s.run('c')\r\n assert_array_equal(c,re)\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n" ]
[ [ "pandas.isnull", "numpy.array", "pandas.testing.assert_frame_equal", "numpy.matrix", "pandas.DataFrame", "numpy.testing.assert_array_equal", "numpy.eye", "numpy.arange", "pandas.Series", "numpy.datetime64" ] ]
chaithyagr/torchkbnufft
[ "3592175fe2d1f611fb2cfec4d4150a850c92605f" ]
[ "torchkbnufft/math.py" ]
[ "import torch\n\n\ndef complex_mult(a, b, dim=0):\n \"\"\"Complex multiplication, real/imag are in dimension dim.\n\n Args:\n a (tensor): A tensor where dimension dim is the complex dimension.\n b (tensor): A tensor where dimension dim is the complex dimension.\n dim (int): An integer indicating the complex dimension.\n\n Returns:\n tensor: a * b, where * executes complex multiplication.\n \"\"\"\n assert a.shape[dim] == 2\n assert b.shape[dim] == 2\n\n real_a = a.select(dim, 0)\n imag_a = a.select(dim, 1)\n real_b = b.select(dim, 0)\n imag_b = b.select(dim, 1)\n\n c = torch.stack(\n (real_a * real_b - imag_a * imag_b, imag_a * real_b + real_a * imag_b), dim\n )\n\n return c\n\n\ndef conj_complex_mult(a, b, dim=0):\n \"\"\"Complex multiplication, real/imag are in dimension dim.\n\n Args:\n a (tensor): A tensor where dimension dim is the complex dimension.\n b (tensor): A tensor where dimension dim is the complex dimension.\n dim (int, default=0): An integer indicating the complex dimension.\n\n Returns:\n tensor: c = a * conj(b), where * executes complex multiplication.\n \"\"\"\n assert a.shape[dim] == 2\n assert b.shape[dim] == 2\n\n real_a = a.select(dim, 0)\n imag_a = a.select(dim, 1)\n real_b = b.select(dim, 0)\n imag_b = b.select(dim, 1)\n\n c = torch.stack(\n (real_a * real_b + imag_a * imag_b, imag_a * real_b - real_a * imag_b), dim\n )\n\n return c\n\n\ndef imag_exp(a, dim=0):\n \"\"\"Imaginary exponential, exp(ia), returns real/imag separate in dim.\n\n Args:\n a (tensor): A tensor where dimension dim is the complex dimension.\n dim (int, default=0): An integer indicating the complex dimension of\n the output.\n\n Returns:\n tensor: c = exp(i*a), where i is sqrt(-1).\n \"\"\"\n c = torch.stack((torch.cos(a), torch.sin(a)), dim)\n\n return c\n\n\ndef inner_product(a, b, dim=0):\n \"\"\"Complex inner product, complex dimension is dim.\n\n Args:\n a (tensor): A tensor where dimension dim is the complex dimension.\n b (tensor): A tensor where dimension dim is the complex dimension.\n dim (int, default=0): An integer indicating the complex dimension.\n\n Returns:\n tensor: The complex inner product of a and b of size 2 (real, imag).\n \"\"\"\n assert a.shape[dim] == 2\n assert b.shape[dim] == 2\n\n inprod = conj_complex_mult(b, a, dim=dim)\n\n real_inprod = inprod.select(dim, 0).sum()\n imag_inprod = inprod.select(dim, 1).sum()\n\n return torch.cat((real_inprod.view(1), imag_inprod.view(1)))\n\n\ndef absolute(t, dim=0):\n \"\"\"Complex absolute value, complex dimension is dim.\n\n Args:\n t (tensor): A tensor where dimension dim is the complex dimension.\n dim (int, default=0): An integer indicating the complex dimension.\n\n Returns:\n tensor: The absolute value of t.\n \"\"\"\n assert t.shape[dim] == 2\n\n abst = torch.sqrt(t.select(dim, 0) ** 2 + t.select(dim, 1) ** 2).unsqueeze(dim)\n\n return abst\n\n\ndef complex_sign(t, dim=0):\n \"\"\"Complex sign function value, complex dimension is dim.\n\n Args:\n t (tensor): A tensor where dimension dim is the complex dimension.\n dim (int, default=0): An integer indicating the complex dimension.\n\n Returns:\n tensor: The complex sign of t.\n \"\"\"\n assert t.shape[dim] == 2\n\n signt = torch.atan2(t.select(dim, 1), t.select(dim, 0))\n signt = imag_exp(signt, dim=dim)\n\n return signt\n" ]
[ [ "torch.cos", "torch.stack", "torch.sin" ] ]
thesombady/PhysicsNum
[ "cb098af9e24fca54dc30562757c461b88bce38b1" ]
[ "PhysicsNum/Linearreg.py" ]
[ "import numpy as np\nimport math\nimport matplotlib.pyplot as plt\n\ndef Linearreg(xlist, ylist):\n \"\"\" Takes two inputs, in list, tuple or arrays and computes a linear regression with method of least squares.\n Returns k, m, such that y = kx + m & maximum deviation. \"\"\" #Add the return of std-error and r^2 value\n if not isinstance((xlist, ylist), (np.generic, np.ndarray)):\n if isinstance((xlist, ylist), (list, tuple)):\n xlist, ylist = np.array(xlist), np.array(ylist)\n else:\n raise TypeError(\"[LinearRegression] Can't make linear fit with given input\")\n if len(xlist) < 2:\n raise TypeError(\"[LinearRegression] Can't make linear fit with given input, add more terms\")\n else:\n Line = lambda k,x,m: k * x + m\n try:\n bline = np.ones(len(xlist))\n A = np.array([xlist, bline]).T\n ATA = A.T.dot(A)\n ATY = A.T.dot(ylist)\n ATAInv = np.linalg.inv(ATA)\n KM = ATAInv.dot(ATY)\n Error = [((KM[0] * xlist[i] + KM[1]) - ylist[i]) for i in range(len(xlist)) if len(xlist) == len(ylist)]\n return KM, max(Error)\n except Exception as E:\n raise E\n #Maximum Deviation, not standard deviation\n\ndef ForceLinearreg(xlist,ylist):\n \"\"\"Linear regression that forces through origion.\"\"\"\n if not isinstance((xlist, ylist), (np.generic, np.ndarray)):\n if isinstance((xlist, ylist), (list, tuple)):\n xlist, ylist = np.array(xlist), np.array(ylist)\n else:\n raise TypeError(\"[ForceLinearreg] Can't make linear fit with given input\")\n if len(xlist) != len(ylist) or len(xlist) < 2 or len(ylist) < 2:\n raise KeyError(\"[ForceLinearreg] Can't make linear fit with given input\")\n else:\n try:\n line = lambda k,x: k * x\n A = np.array([xlist]).T\n ATA = A.T.dot(A)\n ATY = A.T.dot(ylist)\n ATAInv = np.linalg.inv(ATA)\n K = ATAInv.dot(ATY)\n Error = [(K * xlist[i] - ylist[i]) for i in range(len(xlist))]\n return K[0], max(Error)[0]\n except Exception as E:\n raise E\n\n\n\"\"\"\nxlist1 = np.array([1,2,3,4,5,6,7,8,9,10])\nylist1 = np.array([4,6,9,10,12,14,16,18,20,21])\nModel = ForceLinearreg(xlist1, ylist1)\nprint(Model)\nplt.plot(xlist1, ylist1, '.', label = \"DATA\")\nplt.plot(xlist1, xlist1 * Model[0], '-', label = \"Regression\")\nplt.legend()\nplt.show()\n\"\"\"\n\"\"\"\nRegression = Linearregression(xlist1, ylist1)\n\nplt.plot(xlist1,ylist1, '.')\nplt.plot(xlist1, Regression[0] * xlist1 + Regression[1])\nplt.show()\n\"\"\"\n" ]
[ [ "numpy.array", "numpy.linalg.inv" ] ]
JherezTaylor/thesis-preprocessing
[ "7b52ee05af90b451c8bd07c29610cce36e08aa94" ]
[ "hatespeech_core/modules/pattern_classifier/SimpleClassifier.py" ]
[ "import os\n\nimport numpy as np\nimport pandas as pd\n\nfrom .PatternVectorizer import PatternVectorizer\n\nclass SimpleClassifier:\n \n def __init__(self, scoreMatrix, classes=None):\n # scoreMatrix each represent the vector of one pattern\n self.scoreMatrix = scoreMatrix\n \n # Default set classes as integer\n if np.all(classes is None):\n classes = list(range(scoreMatrix.shape[1]))\n if len(classes) < scoreMatrix.shape[1]:\n raise ValueError('Classes dimentions does not fit with the score matrix')\n \n self.classes = classes \n \n def get_top_classes(self, documentPatternVectors, n=1, ascending=True):\n d = 1 if ascending else -1\n return [[self.classes[c] for c in vect[::d][:n]] for vect in self.get_emotion_score(documentPatternVectors).argsort()]\n \n def get_max_score_class(self, documentPatternVectors):\n return [self.classes[c] for c in self.get_emotion_score(documentPatternVectors).argmax(axis=1)]\n \n def get_min_score_class(self, documentPatternVectors):\n return [self.classes[c] for c in self.get_emotion_score(documentPatternVectors).argmin(axis=1)]\n \n def get_emotion_score(self, documentPatternVectors):\n return documentPatternVectors.dot(self.scoreMatrix) \n \n \n @classmethod\n def load_from_folder(cls, patternFolderPath, rank='average', ascending=False):\n patterns_df = pd.DataFrame()\n emotions = []\n for filename in os.listdir(patternFolderPath):\n emotion = filename.replace('tficf_','')\n col = ['pattern', emotion]\n emotions.append(emotion) \n tmp = pd.read_table(os.path.join(patternFolderPath, filename), header=None, names=col)\n if rank:\n tmp[emotion] = tmp[emotion].rank(method=rank, ascending=ascending, pct=True)\n if len(patterns_df) == 0:\n patterns_df = tmp\n else:\n patterns_df = pd.merge(patterns_df, tmp ,on='pattern')\n \n pv = PatternVectorizer(list(patterns_df.pattern))\n new_cls = cls(patterns_df[emotions].values, classes=emotions)\n return (pv, new_cls)\n" ]
[ [ "numpy.all", "pandas.DataFrame", "pandas.merge" ] ]
soichih/TractSeg
[ "f78d0c6dc998905e593cbf4346745467e30d1979" ]
[ "tractseg/libs/Utils.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Copyright 2017 Division of Medical Image Computing, German Cancer Research Center (DKFZ)\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 os, sys\nimport numpy as np\nimport pickle\nimport bz2\nfrom tractseg.libs.Config import Config as C\n\ntry:\n from urllib.request import urlopen # For Python 3.0 and later\nexcept ImportError:\n from urllib2 import urlopen # Fall back to Python 2's urllib2\n\nclass Utils:\n\n @staticmethod\n def invert_x_and_y(affineMatrix):\n '''\n Change sign of x and y transformation (rotation, scaling and transformation)\n\n IMPORTANT note: only done for diagonal elements (if we need rotation (not only scaling) we may also need\n to do it for non-diagonal elements) -> not done yet\n '''\n newAffine = affineMatrix.copy()\n newAffine[0,0] = newAffine[0,0] * -1\n newAffine[1,1] = newAffine[1,1] * -1\n newAffine[0,3] = newAffine[0,3] * -1\n newAffine[1,3] = newAffine[1,3] * -1\n return newAffine\n\n @staticmethod\n def normalize_data(data, where_b0, min_signal=1., out=None):\n \"\"\"\n Normalizes the data with respect to the mean b0 (mean of b0 along z Axis)\n\n method from: https://github.com/nipy/dipy/blob/d0bee8c811daf00c5f9c153168ccbc82fa3b5557/dipy/reconst/shm.py#L741\n \n Ergebnisse schauen mehr verändert aus, als wenn normalize_mean0_std0 mache => besser normalize_mean0_std0 verwenden\n \"\"\"\n if out is None:\n out = np.array(data, dtype='float32', copy=True)\n else:\n if out.dtype.kind != 'f':\n raise ValueError(\"out must be floating point\")\n out[:] = data\n\n #out.clip(min_signal, out=out)\n b0 = out[..., where_b0].mean(-1) #mean(-1) -> mean along the last axis (here: z)\n #print(b0.shape)\n #print(b0[..., None].shape)\n #print(out.shape)\n out /= b0[..., None, None] # original: out /= b0[..., None] -> error dim mismatch\n return out\n\n @staticmethod\n def normalize_mean0_std0(data):\n '''\n Normalizes along all axis for mean=0 and stddev=1\n\n :param data: ndarray, 4D\n :return: ndarray, 4D\n '''\n out = np.array(data, dtype='float32', copy=True)\n\n #mean = 0\n # mean = data.mean((0,1,2,3)) #mean over axis 0,1,2,3\n mean = data.mean() #mean over all axis / over flattened array\n out -= mean\n \n #std = 1\n std = data.std()\n out /= std\n \n return out\n\n @staticmethod\n def to_unit_length(vec):\n '''\n :param vec: 3D vector (\"point\")\n :return: 3D vector with len=1, but same direction as original vector\n '''\n vec_length = np.sqrt(np.sum(np.square(vec)))\n return vec / vec_length # divide elementwise\n\n @staticmethod\n def to_unit_length_batch(vec):\n '''\n :param vec: array of 3D vectors\n :return: array of 3D vectors with len=1, but same direction as original vector\n '''\n vec_length = np.sqrt(np.sum(np.square(vec), axis=1))\n return vec / vec_length[:, np.newaxis] # divide elementwise (only along one axis)\n\n @staticmethod\n def get_lr_decay(epoch_nr):\n '''\n Calc what lr_decay is need to make lr be 1/10 of original lr after epoch_nr number of epochs\n :return: lr_decay\n '''\n target_lr = 0.1 #should be reduced to 1/10 of original\n return target_lr ** (1 / float(epoch_nr))\n\n @staticmethod\n def save_pkl_compressed(filename, myobj):\n \"\"\"\n save object to file using pickle\n\n @param filename: name of destination file\n @type filename: str\n @param myobj: object to save (has to be pickleable)\n @type myobj: obj\n \"\"\"\n try:\n f = bz2.BZ2File(filename, 'wb')\n except IOError as details:\n sys.stderr.write('File ' + filename + ' cannot be written\\n')\n sys.stderr.write(details)\n return\n\n pickle.dump(myobj, f, protocol=2)\n f.close()\n\n @staticmethod\n def load_pkl_compressed(filename):\n \"\"\"\n Load from filename using pickle\n\n @param filename: name of file to load from\n @type filename: str\n \"\"\"\n try:\n f = bz2.BZ2File(filename, 'rb')\n except IOError as details:\n sys.stderr.write('File ' + filename + ' cannot be read\\n')\n sys.stderr.write(details)\n return\n\n myobj = pickle.load(f)\n f.close()\n return myobj\n\n @staticmethod\n def chunks(l, n):\n '''\n Yield successive n-sized chunks from l.\n Last chunk can be smaller.\n '''\n for i in range(0, len(l), n):\n yield l[i:i + n]\n\n @staticmethod\n def flatten(l):\n return [item for sublist in l for item in sublist]\n\n @staticmethod\n def mem_usage(print_usage=True):\n import psutil\n process = psutil.Process()\n gb = process.memory_info().rss / 1e9\n gb = round(gb, 3)\n if print_usage:\n print(\"PID {} using {} GB\".format(os.getpid(), gb))\n return gb\n\n @staticmethod\n def download_pretrained_weights(experiment_type, dropout_sampling=False, part=\"Part1\"):\n\n if experiment_type == \"tract_segmentation\" and dropout_sampling:\n weights_path_old = os.path.join(C.TRACT_SEG_HOME, 'pretrained_weights_tract_segmentation_dropout_v1.npz')\n weights_path = os.path.join(C.TRACT_SEG_HOME, 'pretrained_weights_tract_segmentation_dropout_v2.npz')\n # WEIGHTS_URL = \"https://www.dropbox.com/s/m3ccn286uy1rrhz/TractSeg_Dropout_best_weights_ep488.npz?dl=1\"\n # WEIGHTS_URL = \"https://zenodo.org/record/1409680/files/TractSeg_Dropout_best_weights_ep488.npz?download=1\"\n WEIGHTS_URL = \"https://zenodo.org/record/1414130/files/best_weights_ep407.npz?download=1\"\n\n elif experiment_type == \"tract_segmentation\":\n weights_path_old = os.path.join(C.TRACT_SEG_HOME, 'pretrained_weights_tract_segmentation_v1.npz')\n weights_path = os.path.join(C.TRACT_SEG_HOME, 'pretrained_weights_tract_segmentation_v2.npz')\n # WEIGHTS_URL = \"https://www.dropbox.com/s/nygr0j2zgztedh0/TractSeg_best_weights_ep448.npz?dl=1\"\n # WEIGHTS_URL = \"https://zenodo.org/record/1409684/files/TractSeg_best_weights_ep448.npz?download=1\"\n WEIGHTS_URL = \"https://zenodo.org/record/1410884/files/best_weights_ep274.npz?download=1\"\n\n elif experiment_type == \"endings_segmentation\":\n weights_path_old = os.path.join(C.TRACT_SEG_HOME, 'pretrained_weights_endings_segmentation_v2.npz')\n weights_path = os.path.join(C.TRACT_SEG_HOME, 'pretrained_weights_endings_segmentation_v3.npz')\n # WEIGHTS_URL = \"https://www.dropbox.com/s/dpwdhjkyew8eq4p/EndingsSeg_best_weights_ep423.npz?dl=1\" #old: 20 classes\n # WEIGHTS_URL = \"https://www.dropbox.com/s/l5fa6hhtbv5npvm/EndingsSeg_best_weights_ep176.npz?dl=1\" #old: All classes, CC buggy\n # WEIGHTS_URL = \"https://www.dropbox.com/s/i6a5c5cf6j5ok4r/EndingsSeg_best_weights_ep234.npz?dl=1\"\n WEIGHTS_URL = \"https://zenodo.org/record/1409670/files/EndingsSeg_best_weights_ep234.npz?download=1\"\n\n elif experiment_type == \"dm_regression\":\n weights_path_old = os.path.join(C.TRACT_SEG_HOME, 'pretrained_weights.npz')\n weights_path = os.path.join(C.TRACT_SEG_HOME, 'pretrained_weights_dm_regression_v1.npz')\n # WEIGHTS_URL = \"https://www.dropbox.com/s/d82iv95flz8n5a2/DmReg_best_weights_ep427.npz?dl=1\"\n WEIGHTS_URL = \"https://zenodo.org/record/1409676/files/DmReg_best_weights_ep427.npz?download=1\"\n\n elif experiment_type == \"peak_regression\" and part == \"Part1\":\n weights_path_old = os.path.join(C.TRACT_SEG_HOME, 'pretrained_weights.npz')\n weights_path = os.path.join(C.TRACT_SEG_HOME, 'pretrained_weights_peak_regression_part1_v1.npz')\n WEIGHTS_URL = \"https://zenodo.org/record/1434206/files/best_weights_ep226.npz?download=1\"\n\n elif experiment_type == \"peak_regression\" and part == \"Part2\":\n weights_path_old = os.path.join(C.TRACT_SEG_HOME, 'pretrained_weights.npz')\n weights_path = os.path.join(C.TRACT_SEG_HOME, 'pretrained_weights_peak_regression_part2_v1.npz')\n WEIGHTS_URL = \"https://zenodo.org/record/1434208/files/best_weights_ep210.npz?download=1\"\n\n elif experiment_type == \"peak_regression\" and part == \"Part3\":\n weights_path_old = os.path.join(C.TRACT_SEG_HOME, 'pretrained_weights.npz')\n weights_path = os.path.join(C.TRACT_SEG_HOME, 'pretrained_weights_peak_regression_part3_v1.npz')\n WEIGHTS_URL = \"https://zenodo.org/record/1434210/files/best_weights_ep185.npz?download=1\"\n\n elif experiment_type == \"peak_regression\" and part == \"Part4\":\n weights_path_old = os.path.join(C.TRACT_SEG_HOME, 'pretrained_weights.npz')\n weights_path = os.path.join(C.TRACT_SEG_HOME, 'pretrained_weights_peak_regression_part4_v1.npz')\n WEIGHTS_URL = \"https://zenodo.org/record/1434212/files/best_weights_ep174.npz?download=1\"\n\n\n if os.path.exists(weights_path_old):\n os.remove(weights_path_old)\n\n if WEIGHTS_URL is not None and not os.path.exists(weights_path):\n print(\"Downloading pretrained weights (~140MB) ...\")\n if not os.path.exists(C.TRACT_SEG_HOME):\n os.makedirs(C.TRACT_SEG_HOME)\n\n #This results in an SSL Error on CentOS\n # urllib.urlretrieve(WEIGHTS_URL, weights_path)\n\n data = urlopen(WEIGHTS_URL).read()\n with open(weights_path, \"wb\") as weight_file:\n weight_file.write(data)\n\n\n" ]
[ [ "numpy.square", "numpy.array" ] ]
agolo/haystack
[ "ff6bc38b85ecec3c4d3d7c47b0f2a60da6b1f898" ]
[ "test/benchmarks/results_to_json.py" ]
[ "import json\nimport pandas as pd\nfrom pprint import pprint\n\n\ndef reader(reader_csv=\"reader_results.csv\"):\n model_rename_map = {\n 'deepset/roberta-base-squad2': \"RoBERTa\",\n 'deepset/minilm-uncased-squad2': \"MiniLM\",\n 'deepset/bert-base-cased-squad2': \"BERT base\",\n 'deepset/bert-large-uncased-whole-word-masking-squad2': \"BERT large\",\n 'deepset/xlm-roberta-large-squad2': \"XLM-RoBERTa\",\n }\n\n column_name_map = {\n \"f1\": \"F1\",\n \"passages_per_second\": \"Speed\",\n \"reader\": \"Model\"\n }\n\n df = pd.read_csv(reader_csv)\n df = df[[\"f1\", \"passages_per_second\", \"reader\"]]\n df[\"reader\"] = df[\"reader\"].map(model_rename_map)\n df = df[list(column_name_map)]\n df = df.rename(columns=column_name_map)\n ret = [dict(row) for i, row in df.iterrows()]\n print(\"Reader overview\")\n print(json.dumps(ret, indent=4))\n return ret\n\n\ndef retriever(index_csv=\"retriever_index_results.csv\", query_csv=\"retriever_query_results.csv\"):\n column_name_map = {\n \"model\": \"model\",\n \"n_docs\": \"n_docs\",\n \"docs_per_second\": \"index_speed\",\n \"queries_per_second\": \"query_speed\",\n \"map\": \"map\"\n }\n\n name_cleaning = {\n \"dpr\": \"DPR\",\n \"elastic\": \"BM25\",\n \"elasticsearch\": \"ElasticSearch\",\n \"faiss\": \"FAISS\",\n \"faiss_flat\": \"FAISS (flat)\",\n \"faiss_hnsw\": \"FAISS (HNSW)\",\n \"milvus_flat\": \"Milvus (flat)\",\n \"milvus_hnsw\": \"Milvus (HNSW)\"\n }\n\n index = pd.read_csv(index_csv)\n query = pd.read_csv(query_csv)\n df = pd.merge(index, query,\n how=\"right\",\n left_on=[\"retriever\", \"doc_store\", \"n_docs\"],\n right_on=[\"retriever\", \"doc_store\", \"n_docs\"])\n\n df[\"retriever\"] = df[\"retriever\"].map(name_cleaning)\n df[\"doc_store\"] = df[\"doc_store\"].map(name_cleaning)\n df[\"model\"] = df[\"retriever\"] + \" / \" + df[\"doc_store\"]\n\n df = df[list(column_name_map)]\n df = df.rename(columns=column_name_map)\n\n print(\"Retriever overview\")\n retriever_overview_data = retriever_overview(df)\n print(json.dumps(retriever_overview_data, indent=4))\n\n print(\"Retriever MAP\")\n retriever_map_data = retriever_map(df)\n print(json.dumps(retriever_map_data, indent=4))\n\n print(\"Retriever Speed\")\n retriever_speed_data = retriever_speed(df)\n print(json.dumps(retriever_speed_data, indent=4))\n\n return retriever_overview_data, retriever_map_data, retriever_speed_data\n\n\ndef retriever_map(df):\n columns = [\"model\", \"n_docs\", \"map\"]\n df = df[columns]\n ret = df.to_dict(orient=\"records\")\n return ret\n\n\ndef retriever_speed(df):\n columns = [\"model\", \"n_docs\", \"query_speed\"]\n df = df[columns]\n ret = df.to_dict(orient=\"records\")\n return ret\n\n\ndef retriever_overview(df, chosen_n_docs=100_000):\n df = df[df[\"n_docs\"] == chosen_n_docs]\n ret = [dict(row) for i, row in df.iterrows()]\n return ret\n\n\nif __name__ == \"__main__\":\n reader()\n retriever()" ]
[ [ "pandas.read_csv", "pandas.merge" ] ]