repo_name
stringlengths 8
130
| hexsha
sequence | file_path
sequence | code
sequence | apis
sequence |
---|---|---|---|---|
kmshin1397/kowalski | [
"2aaa4ed7a3b7b400e95227b63c976ce18f7e18eb"
] | [
"kowalski/alert_broker_ztf.py"
] | [
"import argparse\nfrom ast import literal_eval\nfrom astropy.io import fits\nfrom astropy.visualization import (\n AsymmetricPercentileInterval,\n LinearStretch,\n LogStretch,\n ImageNormalize,\n)\nimport base64\nfrom bson.json_util import loads\nimport confluent_kafka\nfrom copy import deepcopy\nimport dask.distributed\nimport datetime\nimport fastavro\nimport gzip\nimport io\nimport matplotlib.pyplot as plt\nimport multiprocessing\nimport numpy as np\nimport os\nimport pandas as pd\nimport pathlib\nimport requests\nfrom requests.packages.urllib3.util.retry import Retry\nimport subprocess\nimport sys\nimport tensorflow as tf\nfrom tensorflow.keras.models import load_model\nimport threading\nimport time\nimport traceback\nfrom typing import Mapping, Optional, Sequence\n\nfrom utils import (\n deg2dms,\n deg2hms,\n great_circle_distance,\n in_ellipse,\n init_db_sync,\n load_config,\n log,\n memoize,\n Mongo,\n radec2lb,\n time_stamp,\n timer,\n TimeoutHTTPAdapter,\n ZTFAlert,\n)\n\n\ntf.config.optimizer.set_jit(True)\n\n\n\"\"\" load config and secrets \"\"\"\nconfig = load_config(config_file=\"config.yaml\")[\"kowalski\"]\n\n\ndef read_schema_data(bytes_io):\n \"\"\"\n Read data that already has an Avro schema.\n\n :param bytes_io: `_io.BytesIO` Data to be decoded.\n :return: `dict` Decoded data.\n \"\"\"\n bytes_io.seek(0)\n message = fastavro.reader(bytes_io)\n return message\n\n\nclass EopError(Exception):\n \"\"\"\n Exception raised when reaching end of a Kafka topic partition.\n \"\"\"\n\n def __init__(self, msg):\n \"\"\"\n :param msg: The Kafka message result from consumer.poll()\n \"\"\"\n message = (\n f\"{time_stamp()}: topic:{msg.topic()}, partition:{msg.partition()}, \"\n f\"status:end, offset:{msg.offset()}, key:{str(msg.key())}\\n\"\n )\n self.message = message\n\n def __str__(self):\n return self.message\n\n\ndef make_photometry(alert: dict, jd_start: float = None):\n \"\"\"\n Make a de-duplicated pandas.DataFrame with photometry of alert['objectId']\n\n :param alert: ZTF alert packet/dict\n :param jd_start:\n :return:\n \"\"\"\n alert = deepcopy(alert)\n df_candidate = pd.DataFrame(alert[\"candidate\"], index=[0])\n\n df_prv_candidates = pd.DataFrame(alert[\"prv_candidates\"])\n df_light_curve = pd.concat(\n [df_candidate, df_prv_candidates], ignore_index=True, sort=False\n )\n\n ztf_filters = {1: \"ztfg\", 2: \"ztfr\", 3: \"ztfi\"}\n df_light_curve[\"ztf_filter\"] = df_light_curve[\"fid\"].apply(lambda x: ztf_filters[x])\n df_light_curve[\"magsys\"] = \"ab\"\n df_light_curve[\"mjd\"] = df_light_curve[\"jd\"] - 2400000.5\n\n df_light_curve[\"mjd\"] = df_light_curve[\"mjd\"].apply(lambda x: np.float64(x))\n df_light_curve[\"magpsf\"] = df_light_curve[\"magpsf\"].apply(lambda x: np.float32(x))\n df_light_curve[\"sigmapsf\"] = df_light_curve[\"sigmapsf\"].apply(\n lambda x: np.float32(x)\n )\n\n df_light_curve = (\n df_light_curve.drop_duplicates(subset=[\"mjd\", \"magpsf\"])\n .reset_index(drop=True)\n .sort_values(by=[\"mjd\"])\n )\n\n # filter out bad data:\n mask_good_diffmaglim = df_light_curve[\"diffmaglim\"] > 0\n df_light_curve = df_light_curve.loc[mask_good_diffmaglim]\n\n # convert from mag to flux\n\n # step 1: calculate the coefficient that determines whether the\n # flux should be negative or positive\n coeff = df_light_curve[\"isdiffpos\"].apply(\n lambda x: 1.0 if x in [True, 1, \"y\", \"Y\", \"t\", \"1\"] else -1.0\n )\n\n # step 2: calculate the flux normalized to an arbitrary AB zeropoint of\n # 23.9 (results in flux in uJy)\n df_light_curve[\"flux\"] = coeff * 10 ** (-0.4 * (df_light_curve[\"magpsf\"] - 23.9))\n\n # step 3: separate detections from non detections\n detected = np.isfinite(df_light_curve[\"magpsf\"])\n undetected = ~detected\n\n # step 4: calculate the flux error\n df_light_curve[\"fluxerr\"] = None # initialize the column\n\n # step 4a: calculate fluxerr for detections using sigmapsf\n df_light_curve.loc[detected, \"fluxerr\"] = np.abs(\n df_light_curve.loc[detected, \"sigmapsf\"]\n * df_light_curve.loc[detected, \"flux\"]\n * np.log(10)\n / 2.5\n )\n\n # step 4b: calculate fluxerr for non detections using diffmaglim\n df_light_curve.loc[undetected, \"fluxerr\"] = (\n 10 ** (-0.4 * (df_light_curve.loc[undetected, \"diffmaglim\"] - 23.9)) / 5.0\n ) # as diffmaglim is the 5-sigma depth\n\n # step 5: set the zeropoint and magnitude system\n df_light_curve[\"zp\"] = 23.9\n df_light_curve[\"zpsys\"] = \"ab\"\n\n # only \"new\" photometry requested?\n if jd_start is not None:\n w_after_jd = df_light_curve[\"jd\"] > jd_start\n df_light_curve = df_light_curve.loc[w_after_jd]\n\n return df_light_curve\n\n\ndef make_thumbnail(alert, ttype: str, ztftype: str):\n \"\"\"\n Convert lossless FITS cutouts from ZTF alerts into PNGs\n\n :param alert: ZTF alert packet/dict\n :param ttype: <new|ref|sub>\n :param ztftype: <Science|Template|Difference>\n :return:\n \"\"\"\n alert = deepcopy(alert)\n\n cutout_data = alert[f\"cutout{ztftype}\"][\"stampData\"]\n with gzip.open(io.BytesIO(cutout_data), \"rb\") as f:\n with fits.open(io.BytesIO(f.read())) as hdu:\n # header = hdu[0].header\n data_flipped_y = np.flipud(hdu[0].data)\n # fixme: png, switch to fits eventually\n buff = io.BytesIO()\n plt.close(\"all\")\n fig = plt.figure()\n fig.set_size_inches(4, 4, forward=False)\n ax = plt.Axes(fig, [0.0, 0.0, 1.0, 1.0])\n ax.set_axis_off()\n fig.add_axes(ax)\n\n # replace nans with median:\n img = np.array(data_flipped_y)\n # replace dubiously large values\n xl = np.greater(np.abs(img), 1e20, where=~np.isnan(img))\n if img[xl].any():\n img[xl] = np.nan\n if np.isnan(img).any():\n median = float(np.nanmean(img.flatten()))\n img = np.nan_to_num(img, nan=median)\n\n norm = ImageNormalize(\n img, stretch=LinearStretch() if ztftype == \"Difference\" else LogStretch()\n )\n img_norm = norm(img)\n normalizer = AsymmetricPercentileInterval(lower_percentile=1, upper_percentile=100)\n vmin, vmax = normalizer.get_limits(img_norm)\n ax.imshow(img_norm, cmap=\"bone\", origin=\"lower\", vmin=vmin, vmax=vmax)\n plt.savefig(buff, dpi=42)\n\n buff.seek(0)\n plt.close(\"all\")\n\n thumb = {\n \"obj_id\": alert[\"objectId\"],\n \"data\": base64.b64encode(buff.read()).decode(\"utf-8\"),\n \"ttype\": ttype,\n }\n\n return thumb\n\n\n\"\"\" Alert filters \"\"\"\n\n\ndef make_triplet(alert, to_tpu: bool = False):\n \"\"\"\n Make an L2-normalized cutout triplet out of a ZTF alert\n\n :param alert:\n :param to_tpu:\n :return:\n \"\"\"\n cutout_dict = dict()\n\n for cutout in (\"science\", \"template\", \"difference\"):\n cutout_data = alert[f\"cutout{cutout.capitalize()}\"][\"stampData\"]\n\n # unzip\n with gzip.open(io.BytesIO(cutout_data), \"rb\") as f:\n with fits.open(io.BytesIO(f.read())) as hdu:\n data = hdu[0].data\n # replace nans with zeros\n cutout_dict[cutout] = np.nan_to_num(data)\n # L2-normalize\n cutout_dict[cutout] /= np.linalg.norm(cutout_dict[cutout])\n\n # pad to 63x63 if smaller\n shape = cutout_dict[cutout].shape\n if shape != (63, 63):\n # print(f'Shape of {candid}/{cutout}: {shape}, padding to (63, 63)')\n cutout_dict[cutout] = np.pad(\n cutout_dict[cutout],\n [(0, 63 - shape[0]), (0, 63 - shape[1])],\n mode=\"constant\",\n constant_values=1e-9,\n )\n\n triplet = np.zeros((63, 63, 3))\n triplet[:, :, 0] = cutout_dict[\"science\"]\n triplet[:, :, 1] = cutout_dict[\"template\"]\n triplet[:, :, 2] = cutout_dict[\"difference\"]\n\n if to_tpu:\n # Edge TPUs require additional processing\n triplet = np.rint(triplet * 128 + 128).astype(np.uint8).flatten()\n\n return triplet\n\n\ndef alert_filter__ml(alert, ml_models: dict = None) -> dict:\n \"\"\"Execute ML models on a ZTF alert\n\n :param alert:\n :param ml_models:\n :return:\n \"\"\"\n\n scores = dict()\n\n if ml_models is not None and len(ml_models) > 0:\n try:\n with timer(\"ZTFAlert(alert)\"):\n ztf_alert = ZTFAlert(alert)\n with timer(\"Prepping features\"):\n features = np.expand_dims(ztf_alert.data[\"features\"], axis=[0, -1])\n triplet = np.expand_dims(ztf_alert.data[\"triplet\"], axis=[0])\n\n # braai\n if \"braai\" in ml_models.keys():\n with timer(\"braai\"):\n braai = ml_models[\"braai\"][\"model\"].predict(x=triplet)[0]\n scores[\"braai\"] = float(braai)\n scores[\"braai_version\"] = ml_models[\"braai\"][\"version\"]\n # acai\n for model_name in (\"acai_h\", \"acai_v\", \"acai_o\", \"acai_n\", \"acai_b\"):\n if model_name in ml_models.keys():\n with timer(model_name):\n score = ml_models[model_name][\"model\"].predict(\n [features, triplet]\n )[0]\n scores[model_name] = float(score)\n scores[f\"{model_name}_version\"] = ml_models[model_name][\n \"version\"\n ]\n except Exception as e:\n log(str(e))\n\n return scores\n\n\n# cone search radius:\ncone_search_radius = float(config[\"database\"][\"xmatch\"][\"cone_search_radius\"])\n# convert to rad:\nif config[\"database\"][\"xmatch\"][\"cone_search_unit\"] == \"arcsec\":\n cone_search_radius *= np.pi / 180.0 / 3600.0\nelif config[\"database\"][\"xmatch\"][\"cone_search_unit\"] == \"arcmin\":\n cone_search_radius *= np.pi / 180.0 / 60.0\nelif config[\"database\"][\"xmatch\"][\"cone_search_unit\"] == \"deg\":\n cone_search_radius *= np.pi / 180.0\nelif config[\"database\"][\"xmatch\"][\"cone_search_unit\"] == \"rad\":\n cone_search_radius *= 1\nelse:\n raise Exception(\"Unknown cone search unit. Must be in [deg, rad, arcsec, arcmin]\")\n\n\ndef alert_filter__xmatch(database, alert) -> dict:\n \"\"\"\n Cross-match alerts\n \"\"\"\n\n xmatches = dict()\n\n try:\n ra_geojson = float(alert[\"candidate\"][\"ra\"])\n # geojson-friendly ra:\n ra_geojson -= 180.0\n dec_geojson = float(alert[\"candidate\"][\"dec\"])\n\n \"\"\" catalogs \"\"\"\n for catalog in config[\"database\"][\"xmatch\"][\"catalogs\"]:\n catalog_filter = config[\"database\"][\"xmatch\"][\"catalogs\"][catalog][\"filter\"]\n catalog_projection = config[\"database\"][\"xmatch\"][\"catalogs\"][catalog][\n \"projection\"\n ]\n\n object_position_query = dict()\n object_position_query[\"coordinates.radec_geojson\"] = {\n \"$geoWithin\": {\n \"$centerSphere\": [[ra_geojson, dec_geojson], cone_search_radius]\n }\n }\n s = database[catalog].find(\n {**object_position_query, **catalog_filter}, {**catalog_projection}\n )\n xmatches[catalog] = list(s)\n\n except Exception as e:\n log(str(e))\n\n return xmatches\n\n\n# cone search radius in deg:\ncone_search_radius_clu = 3.0\n# convert deg to rad:\ncone_search_radius_clu *= np.pi / 180.0\n\n\ndef alert_filter__xmatch_clu(\n database, alert, size_margin=3, clu_version=\"CLU_20190625\"\n) -> dict:\n \"\"\"\n Run cross-match with the CLU catalog\n\n :param database:\n :param alert:\n :param size_margin: multiply galaxy size by this much before looking for a match\n :param clu_version: CLU catalog version\n :return:\n \"\"\"\n\n xmatches = dict()\n\n try:\n ra = float(alert[\"candidate\"][\"ra\"])\n dec = float(alert[\"candidate\"][\"dec\"])\n\n # geojson-friendly ra:\n ra_geojson = float(alert[\"candidate\"][\"ra\"]) - 180.0\n dec_geojson = dec\n\n catalog_filter = {}\n catalog_projection = {\n \"_id\": 1,\n \"name\": 1,\n \"ra\": 1,\n \"dec\": 1,\n \"a\": 1,\n \"b2a\": 1,\n \"pa\": 1,\n \"z\": 1,\n \"sfr_fuv\": 1,\n \"mstar\": 1,\n \"sfr_ha\": 1,\n \"coordinates.radec_str\": 1,\n }\n\n # first do a coarse search of everything that is around\n object_position_query = dict()\n object_position_query[\"coordinates.radec_geojson\"] = {\n \"$geoWithin\": {\n \"$centerSphere\": [[ra_geojson, dec_geojson], cone_search_radius_clu]\n }\n }\n galaxies = list(\n database[clu_version].find(\n {**object_position_query, **catalog_filter}, {**catalog_projection}\n )\n )\n\n # these guys are very big, so check them separately\n M31 = {\n \"_id\": 596900,\n \"name\": \"PGC2557\",\n \"ra\": 10.6847,\n \"dec\": 41.26901,\n \"a\": 6.35156,\n \"b2a\": 0.32,\n \"pa\": 35.0,\n \"z\": -0.00100100006,\n \"sfr_fuv\": None,\n \"mstar\": 253816876.412914,\n \"sfr_ha\": 0,\n \"coordinates\": {\"radec_str\": [\"00:42:44.3503\", \"41:16:08.634\"]},\n }\n M33 = {\n \"_id\": 597543,\n \"name\": \"PGC5818\",\n \"ra\": 23.46204,\n \"dec\": 30.66022,\n \"a\": 2.35983,\n \"b2a\": 0.59,\n \"pa\": 23.0,\n \"z\": -0.000597000006,\n \"sfr_fuv\": None,\n \"mstar\": 4502777.420493,\n \"sfr_ha\": 0,\n \"coordinates\": {\"radec_str\": [\"01:33:50.8900\", \"30:39:36.800\"]},\n }\n\n # do elliptical matches\n matches = []\n\n for galaxy in galaxies + [M31, M33]:\n alpha1, delta01 = galaxy[\"ra\"], galaxy[\"dec\"]\n\n redshift = galaxy[\"z\"]\n # By default, set the cross-match radius to 50 kpc at the redshift of the host galaxy\n cm_radius = 50.0 * (0.05 / redshift) / 3600\n if redshift < 0.01:\n # for nearby galaxies and galaxies with negative redshifts, do a 5 arc-minute cross-match\n # (cross-match radius would otherwise get un-physically large for nearby galaxies)\n cm_radius = 300.0 / 3600\n\n in_galaxy = in_ellipse(ra, dec, alpha1, delta01, cm_radius, 1, 0)\n\n if in_galaxy:\n match = galaxy\n distance_arcsec = round(\n great_circle_distance(ra, dec, alpha1, delta01) * 3600, 2\n )\n # also add a physical distance parameter for redshifts in the Hubble flow\n if redshift > 0.005:\n distance_kpc = round(\n great_circle_distance(ra, dec, alpha1, delta01)\n * 3600\n * (redshift / 0.05),\n 2,\n )\n else:\n distance_kpc = -1\n\n match[\"coordinates\"][\"distance_arcsec\"] = distance_arcsec\n match[\"coordinates\"][\"distance_kpc\"] = distance_kpc\n matches.append(match)\n\n xmatches[clu_version] = matches\n\n except Exception as e:\n log(str(e))\n\n return xmatches\n\n\ndef alert_filter__user_defined(\n database,\n filter_templates,\n alert,\n catalog: str = \"ZTF_alerts\",\n max_time_ms: int = 500,\n) -> list:\n \"\"\"\n Evaluate user-defined filters\n\n :param database:\n :param filter_templates:\n :param alert:\n :param catalog:\n :param max_time_ms:\n :return:\n \"\"\"\n passed_filters = []\n\n for filter_template in filter_templates:\n try:\n _filter = deepcopy(filter_template)\n # match candid\n _filter[\"pipeline\"][0][\"$match\"][\"candid\"] = alert[\"candid\"]\n\n filtered_data = list(\n database[catalog].aggregate(\n _filter[\"pipeline\"], allowDiskUse=False, maxTimeMS=max_time_ms\n )\n )\n # passed filter? then len(passed_filter) must be = 1\n if len(filtered_data) == 1:\n log(\n f'{alert[\"objectId\"]} {alert[\"candid\"]} passed filter {_filter[\"fid\"]}'\n )\n passed_filters.append(\n {\n \"group_id\": _filter[\"group_id\"],\n \"filter_id\": _filter[\"filter_id\"],\n \"group_name\": _filter[\"group_name\"],\n \"filter_name\": _filter[\"filter_name\"],\n \"fid\": _filter[\"fid\"],\n \"permissions\": _filter[\"permissions\"],\n \"autosave\": _filter[\"autosave\"],\n \"update_annotations\": _filter[\"update_annotations\"],\n \"data\": filtered_data[0],\n }\n )\n\n except Exception as e:\n log(\n f'Filter {filter_template[\"fid\"]} execution failed on alert {alert[\"candid\"]}: {e}'\n )\n continue\n\n return passed_filters\n\n\ndef process_alert(record, topic):\n \"\"\"Alert brokering task run by dask.distributed workers\n\n :param record: decoded alert from IPAC's Kafka stream\n :param topic: Kafka stream topic name for bookkeeping\n :return:\n \"\"\"\n candid = record[\"candid\"]\n objectId = record[\"objectId\"]\n\n # get worker running current task\n worker = dask.distributed.get_worker()\n alert_worker = worker.plugins[\"worker-init\"].alert_worker\n\n log(f\"{topic} {objectId} {candid} {worker.address}\")\n\n # return if this alert packet has already been processed and ingested into collection_alerts:\n if (\n alert_worker.mongo.db[alert_worker.collection_alerts].count_documents(\n {\"candid\": candid}, limit=1\n )\n == 1\n ):\n return\n\n # candid not in db, ingest decoded avro packet into db\n # todo: ?? restructure alerts even further?\n # move cutouts to ZTF_alerts_cutouts? reduce the main db size for performance\n # group by objectId similar to prv_candidates?? maybe this is too much\n with timer(f\"Mongification of {objectId} {candid}\", alert_worker.verbose > 1):\n alert, prv_candidates = alert_worker.alert_mongify(record)\n\n # ML models:\n with timer(f\"MLing of {objectId} {candid}\", alert_worker.verbose > 1):\n scores = alert_filter__ml(record, ml_models=alert_worker.ml_models)\n alert[\"classifications\"] = scores\n\n with timer(f\"Ingesting {objectId} {candid}\", alert_worker.verbose > 1):\n alert_worker.mongo.insert_one(\n collection=alert_worker.collection_alerts, document=alert\n )\n\n # prv_candidates: pop nulls - save space\n prv_candidates = [\n {kk: vv for kk, vv in prv_candidate.items() if vv is not None}\n for prv_candidate in prv_candidates\n ]\n\n # cross-match with external catalogs if objectId not in collection_alerts_aux:\n if (\n alert_worker.mongo.db[alert_worker.collection_alerts_aux].count_documents(\n {\"_id\": objectId}, limit=1\n )\n == 0\n ):\n with timer(f\"Cross-match of {objectId} {candid}\", alert_worker.verbose > 1):\n xmatches = alert_filter__xmatch(alert_worker.mongo.db, alert)\n # CLU cross-match:\n with timer(f\"CLU cross-match {objectId} {candid}\", alert_worker.verbose > 1):\n xmatches = {\n **xmatches,\n **alert_filter__xmatch_clu(alert_worker.mongo.db, alert),\n }\n\n alert_aux = {\n \"_id\": objectId,\n \"cross_matches\": xmatches,\n \"prv_candidates\": prv_candidates,\n }\n\n with timer(f\"Aux ingesting {objectId} {candid}\", alert_worker.verbose > 1):\n alert_worker.mongo.insert_one(\n collection=alert_worker.collection_alerts_aux, document=alert_aux\n )\n\n else:\n with timer(f\"Aux updating of {objectId} {candid}\", alert_worker.verbose > 1):\n alert_worker.mongo.db[alert_worker.collection_alerts_aux].update_one(\n {\"_id\": objectId},\n {\"$addToSet\": {\"prv_candidates\": {\"$each\": prv_candidates}}},\n upsert=True,\n )\n\n if config[\"misc\"][\"broker\"]:\n # execute user-defined alert filters\n with timer(f\"Filtering of {objectId} {candid}\", alert_worker.verbose > 1):\n passed_filters = alert_filter__user_defined(\n alert_worker.mongo.db, alert_worker.filter_templates, alert\n )\n if alert_worker.verbose > 1:\n log(f\"{objectId} {candid} number of filters passed: {len(passed_filters)}\")\n\n # post to SkyPortal\n alert_worker.alert_sentinel_skyportal(alert, prv_candidates, passed_filters)\n\n # clean up after thyself\n del record, alert, prv_candidates\n\n\nclass AlertConsumer:\n \"\"\"\n Creates an alert stream Kafka consumer for a given topic.\n \"\"\"\n\n def __init__(self, topic, dask_client, **kwargs):\n\n self.verbose = kwargs.get(\"verbose\", 2)\n\n self.dask_client = dask_client\n\n # keep track of disconnected partitions\n self.num_disconnected_partitions = 0\n self.topic = topic\n\n def error_cb(err, _self=self):\n log(f\"error_cb --------> {err}\")\n # print(err.code())\n if err.code() == -195:\n _self.num_disconnected_partitions += 1\n if _self.num_disconnected_partitions == _self.num_partitions:\n log(\"All partitions got disconnected, killing thread\")\n sys.exit()\n else:\n log(\n f\"{_self.topic}: disconnected from partition. total: {_self.num_disconnected_partitions}\"\n )\n\n # 'error_cb': error_cb\n kwargs[\"error_cb\"] = error_cb\n\n self.consumer = confluent_kafka.Consumer(**kwargs)\n self.num_partitions = 0\n\n def on_assign(consumer, partitions, _self=self):\n # force-reset offsets when subscribing to a topic:\n for part in partitions:\n # -2 stands for beginning and -1 for end\n part.offset = -2\n # keep number of partitions.\n # when reaching end of last partition, kill thread and start from beginning\n _self.num_partitions += 1\n log(consumer.get_watermark_offsets(part))\n\n self.consumer.subscribe([topic], on_assign=on_assign)\n\n # set up own mongo client\n self.collection_alerts = config[\"database\"][\"collections\"][\"alerts_ztf\"]\n\n self.mongo = Mongo(\n host=config[\"database\"][\"host\"],\n port=config[\"database\"][\"port\"],\n replica_set=config[\"database\"][\"replica_set\"],\n username=config[\"database\"][\"username\"],\n password=config[\"database\"][\"password\"],\n db=config[\"database\"][\"db\"],\n verbose=self.verbose,\n )\n\n # create indexes\n if config[\"database\"][\"build_indexes\"]:\n for index in config[\"database\"][\"indexes\"][self.collection_alerts]:\n try:\n ind = [tuple(ii) for ii in index[\"fields\"]]\n self.mongo.db[self.collection_alerts].create_index(\n keys=ind,\n name=index[\"name\"],\n background=True,\n unique=index[\"unique\"],\n )\n except Exception as e:\n log(e)\n\n @staticmethod\n def decode_message(msg):\n \"\"\"\n Decode Avro message according to a schema.\n\n :param msg: The Kafka message result from consumer.poll()\n :return:\n \"\"\"\n message = msg.value()\n decoded_msg = message\n\n try:\n bytes_io = io.BytesIO(message)\n decoded_msg = read_schema_data(bytes_io)\n except AssertionError:\n decoded_msg = None\n except IndexError:\n literal_msg = literal_eval(\n str(message, encoding=\"utf-8\")\n ) # works to give bytes\n bytes_io = io.BytesIO(literal_msg) # works to give <class '_io.BytesIO'>\n decoded_msg = read_schema_data(bytes_io) # yields reader\n except Exception:\n decoded_msg = message\n finally:\n return decoded_msg\n\n def poll(self):\n \"\"\"\n Polls Kafka broker to consume a topic.\n\n :return:\n \"\"\"\n msg = self.consumer.poll()\n\n if msg is None:\n log(\"Caught error: msg is None\")\n\n if msg.error():\n log(f\"Caught error: {msg.error()}\")\n raise EopError(msg)\n\n elif msg is not None:\n try:\n # decode avro packet\n with timer(\"Decoding alert\", self.verbose > 1):\n msg_decoded = self.decode_message(msg)\n\n for record in msg_decoded:\n # submit only unprocessed alerts:\n if (\n self.mongo.db[self.collection_alerts].count_documents(\n {\"candid\": record[\"candid\"]}, limit=1\n )\n == 0\n ):\n with timer(\n f\"Submitting alert {record['objectId']} {record['candid']} for processing\",\n self.verbose > 1,\n ):\n future = self.dask_client.submit(\n process_alert, record, self.topic, pure=True\n )\n dask.distributed.fire_and_forget(future)\n future.release()\n del future\n\n except Exception as e:\n log(e)\n _err = traceback.format_exc()\n log(_err)\n\n\nclass AlertWorker:\n \"\"\"Tools to handle alert processing: database ingestion, filtering, ml'ing, cross-matches, reporting to SP\"\"\"\n\n def __init__(self, **kwargs):\n\n self.verbose = kwargs.get(\"verbose\", 2)\n self.config = config\n\n # Kowalski version\n path_version_file = pathlib.Path(__file__).parent.absolute() / \"version.txt\"\n version = f\"v{self.config['server']['version']}\"\n if path_version_file.exists():\n with open(\n pathlib.Path(__file__).parent.absolute() / \"version.txt\", \"r\"\n ) as version_file:\n version = version_file.read().strip()\n\n # MongoDB collections to store the alerts:\n self.collection_alerts = self.config[\"database\"][\"collections\"][\"alerts_ztf\"]\n self.collection_alerts_aux = self.config[\"database\"][\"collections\"][\n \"alerts_ztf_aux\"\n ]\n self.collection_alerts_filter = self.config[\"database\"][\"collections\"][\n \"alerts_ztf_filter\"\n ]\n\n self.mongo = Mongo(\n host=config[\"database\"][\"host\"],\n port=config[\"database\"][\"port\"],\n replica_set=config[\"database\"][\"replica_set\"],\n username=config[\"database\"][\"username\"],\n password=config[\"database\"][\"password\"],\n db=config[\"database\"][\"db\"],\n verbose=self.verbose,\n )\n\n # ML models\n self.ml_models = dict()\n for model in config[\"ml_models\"]:\n try:\n model_version = config[\"ml_models\"][model][\"version\"]\n # todo: allow other formats such as SavedModel\n model_filepath = os.path.join(\n config[\"path\"][\"ml_models\"], f\"{model}.{model_version}.h5\"\n )\n self.ml_models[model] = {\n \"model\": load_model(model_filepath),\n \"version\": model_version,\n }\n except Exception as e:\n log(f\"Error loading ML model {model}: {str(e)}\")\n _err = traceback.format_exc()\n log(_err)\n continue\n\n # talking to SkyPortal?\n if not config[\"misc\"][\"broker\"]:\n return\n\n # session to talk to SkyPortal\n self.session = requests.Session()\n self.session_headers = {\n \"Authorization\": f\"token {config['skyportal']['token']}\",\n \"User-Agent\": f\"Kowalski {version}\",\n }\n\n retries = Retry(\n total=5,\n backoff_factor=2,\n status_forcelist=[405, 429, 500, 502, 503, 504],\n method_whitelist=[\"HEAD\", \"GET\", \"PUT\", \"POST\", \"PATCH\"],\n )\n adapter = TimeoutHTTPAdapter(timeout=5, max_retries=retries)\n self.session.mount(\"https://\", adapter)\n self.session.mount(\"http://\", adapter)\n\n # get ZTF instrument id\n self.instrument_id = 1\n with timer(\"Getting ZTF instrument_id from SkyPortal\", self.verbose > 1):\n response = self.api_skyportal(\"GET\", \"/api/instrument\", {\"name\": \"ZTF\"})\n if response.json()[\"status\"] == \"success\" and len(response.json()[\"data\"]) > 0:\n self.instrument_id = response.json()[\"data\"][0][\"id\"]\n log(f\"Got ZTF instrument_id from SkyPortal: {self.instrument_id}\")\n else:\n log(\"Failed to get ZTF instrument_id from SkyPortal\")\n raise ValueError(\"Failed to get ZTF instrument_id from SkyPortal\")\n\n # get ZTF alert stream ids to program ids mapping\n self.ztf_program_id_to_stream_id = dict()\n with timer(\"Getting ZTF alert stream ids from SkyPortal\", self.verbose > 1):\n response = self.api_skyportal(\"GET\", \"/api/streams\")\n if response.json()[\"status\"] == \"success\" and len(response.json()[\"data\"]) > 0:\n for stream in response.json()[\"data\"]:\n if stream.get(\"name\") == \"ZTF Public\":\n self.ztf_program_id_to_stream_id[1] = stream[\"id\"]\n if stream.get(\"name\") == \"ZTF Public+Partnership\":\n self.ztf_program_id_to_stream_id[2] = stream[\"id\"]\n if stream.get(\"name\") == \"ZTF Public+Partnership+Caltech\":\n # programid=0 is engineering data\n self.ztf_program_id_to_stream_id[0] = stream[\"id\"]\n self.ztf_program_id_to_stream_id[3] = stream[\"id\"]\n if len(self.ztf_program_id_to_stream_id) != 4:\n log(\"Failed to map ZTF alert stream ids from SkyPortal to program ids\")\n raise ValueError(\n \"Failed to map ZTF alert stream ids from SkyPortal to program ids\"\n )\n log(\n f\"Got ZTF program id to SP stream id mapping: {self.ztf_program_id_to_stream_id}\"\n )\n else:\n log(\"Failed to get ZTF alert stream ids from SkyPortal\")\n raise ValueError(\"Failed to get ZTF alert stream ids from SkyPortal\")\n\n # filter pipeline upstream: select current alert, ditch cutouts, and merge with aux data\n # including archival photometry and cross-matches:\n self.filter_pipeline_upstream = config[\"database\"][\"filters\"][\n self.collection_alerts\n ]\n log(\"Upstream filtering pipeline:\")\n log(self.filter_pipeline_upstream)\n\n # load *active* user-defined alert filter templates and pre-populate them\n active_filters = self.get_active_filters()\n self.filter_templates = self.make_filter_templates(active_filters)\n\n # set up watchdog for periodic refresh of the filter templates, in case those change\n self.filter_monitor = threading.Thread(target=self.reload_filters)\n self.filter_monitor.start()\n\n log(\"Loaded user-defined filters:\")\n log(self.filter_templates)\n\n def api_skyportal(self, method: str, endpoint: str, data: Optional[Mapping] = None):\n \"\"\"Make an API call to a SkyPortal instance\n\n :param method:\n :param endpoint:\n :param data:\n :return:\n \"\"\"\n method = method.lower()\n methods = {\n \"head\": self.session.head,\n \"get\": self.session.get,\n \"post\": self.session.post,\n \"put\": self.session.put,\n \"patch\": self.session.patch,\n \"delete\": self.session.delete,\n }\n\n if endpoint is None:\n raise ValueError(\"Endpoint not specified\")\n if method not in [\"head\", \"get\", \"post\", \"put\", \"patch\", \"delete\"]:\n raise ValueError(f\"Unsupported method: {method}\")\n\n if method == \"get\":\n response = methods[method](\n f\"{config['skyportal']['protocol']}://\"\n f\"{config['skyportal']['host']}:{config['skyportal']['port']}\"\n f\"{endpoint}\",\n params=data,\n headers=self.session_headers,\n )\n else:\n response = methods[method](\n f\"{config['skyportal']['protocol']}://\"\n f\"{config['skyportal']['host']}:{config['skyportal']['port']}\"\n f\"{endpoint}\",\n json=data,\n headers=self.session_headers,\n )\n\n return response\n\n @memoize\n def api_skyportal_get_group(self, group_id):\n return self.api_skyportal(\n \"GET\", f\"/api/groups/{group_id}?includeGroupUsers=False\"\n )\n\n def get_active_filters(self):\n \"\"\"\n Fetch user-defined filters from own db marked as active\n\n :return:\n \"\"\"\n # todo: query SP to make sure the filters still exist there and we're not out of sync;\n # clean up if necessary\n return list(\n self.mongo.db[config[\"database\"][\"collections\"][\"filters\"]].aggregate(\n [\n {\n \"$match\": {\n \"catalog\": config[\"database\"][\"collections\"][\"alerts_ztf\"],\n \"active\": True,\n }\n },\n {\n \"$project\": {\n \"group_id\": 1,\n \"filter_id\": 1,\n \"permissions\": 1,\n \"autosave\": 1,\n \"update_annotations\": 1,\n \"fv\": {\n \"$arrayElemAt\": [\n {\n \"$filter\": {\n \"input\": \"$fv\",\n \"as\": \"fvv\",\n \"cond\": {\n \"$eq\": [\"$$fvv.fid\", \"$active_fid\"]\n },\n }\n },\n 0,\n ]\n },\n }\n },\n ]\n )\n )\n\n def make_filter_templates(self, active_filters: Sequence):\n \"\"\"\n Make filter templates by adding metadata, prepending upstream aggregation stages and setting permissions\n\n :param active_filters:\n :return:\n \"\"\"\n filter_templates = []\n for active_filter in active_filters:\n try:\n # collect additional info from SkyPortal\n with timer(\n f\"Getting info on group id={active_filter['group_id']} from SkyPortal\",\n self.verbose > 1,\n ):\n response = self.api_skyportal_get_group(active_filter[\"group_id\"])\n if self.verbose > 1:\n log(response.json())\n if response.json()[\"status\"] == \"success\":\n group_name = (\n response.json()[\"data\"][\"nickname\"]\n if response.json()[\"data\"][\"nickname\"] is not None\n else response.json()[\"data\"][\"name\"]\n )\n filter_name = [\n filtr[\"name\"]\n for filtr in response.json()[\"data\"][\"filters\"]\n if filtr[\"id\"] == active_filter[\"filter_id\"]\n ][0]\n else:\n log(\n f\"Failed to get info on group id={active_filter['group_id']} from SkyPortal\"\n )\n group_name, filter_name = None, None\n # raise ValueError(f\"Failed to get info on group id={active_filter['group_id']} from SkyPortal\")\n log(f\"Group name: {group_name}, filter name: {filter_name}\")\n\n # prepend upstream aggregation stages:\n pipeline = deepcopy(self.filter_pipeline_upstream) + loads(\n active_filter[\"fv\"][\"pipeline\"]\n )\n # set permissions\n pipeline[0][\"$match\"][\"candidate.programid\"][\"$in\"] = active_filter[\n \"permissions\"\n ]\n pipeline[3][\"$project\"][\"prv_candidates\"][\"$filter\"][\"cond\"][\"$and\"][0][\n \"$in\"\n ][1] = active_filter[\"permissions\"]\n\n filter_template = {\n \"group_id\": active_filter[\"group_id\"],\n \"filter_id\": active_filter[\"filter_id\"],\n \"group_name\": group_name,\n \"filter_name\": filter_name,\n \"fid\": active_filter[\"fv\"][\"fid\"],\n \"permissions\": active_filter[\"permissions\"],\n \"autosave\": active_filter[\"autosave\"],\n \"update_annotations\": active_filter[\"update_annotations\"],\n \"pipeline\": deepcopy(pipeline),\n }\n\n filter_templates.append(filter_template)\n except Exception as e:\n log(\n \"Failed to generate filter template for \"\n f\"group_id={active_filter['group_id']} filter_id={active_filter['filter_id']}: {e}\"\n )\n continue\n\n return filter_templates\n\n def reload_filters(self):\n \"\"\"\n Helper function to periodically reload filters from SkyPortal\n\n :return:\n \"\"\"\n while True:\n time.sleep(60 * 5)\n\n active_filters = self.get_active_filters()\n self.filter_templates = self.make_filter_templates(active_filters)\n\n @staticmethod\n def alert_mongify(alert: Mapping):\n \"\"\"\n Prepare a raw ZTF alert for ingestion into MongoDB:\n - add a placeholder for ML-based classifications\n - add coordinates for 2D spherical indexing and compute Galactic coordinates\n - cut off the prv_candidates section\n\n :param alert:\n :return:\n \"\"\"\n\n doc = dict(alert)\n\n # let mongo create a unique _id\n\n # placeholders for classifications\n doc[\"classifications\"] = dict()\n\n # GeoJSON for 2D indexing\n doc[\"coordinates\"] = {}\n _ra = doc[\"candidate\"][\"ra\"]\n _dec = doc[\"candidate\"][\"dec\"]\n # string format: H:M:S, D:M:S\n _radec_str = [deg2hms(_ra), deg2dms(_dec)]\n doc[\"coordinates\"][\"radec_str\"] = _radec_str\n # for GeoJSON, must be lon:[-180, 180], lat:[-90, 90] (i.e. in deg)\n _radec_geojson = [_ra - 180.0, _dec]\n doc[\"coordinates\"][\"radec_geojson\"] = {\n \"type\": \"Point\",\n \"coordinates\": _radec_geojson,\n }\n\n # Galactic coordinates l and b\n l, b = radec2lb(doc[\"candidate\"][\"ra\"], doc[\"candidate\"][\"dec\"])\n doc[\"coordinates\"][\"l\"] = l\n doc[\"coordinates\"][\"b\"] = b\n\n prv_candidates = deepcopy(doc[\"prv_candidates\"])\n doc.pop(\"prv_candidates\", None)\n if prv_candidates is None:\n prv_candidates = []\n\n return doc, prv_candidates\n\n def alert_post_candidate(self, alert: Mapping, filter_ids: Sequence):\n \"\"\"\n Post a ZTF alert as a candidate for filters on SkyPortal\n :param alert:\n :param filter_ids:\n :return:\n \"\"\"\n # post metadata with all filter_ids in single call to /api/candidates\n alert_thin = {\n \"id\": alert[\"objectId\"],\n \"ra\": alert[\"candidate\"].get(\"ra\"),\n \"dec\": alert[\"candidate\"].get(\"dec\"),\n \"score\": alert[\"candidate\"].get(\"drb\", alert[\"candidate\"][\"rb\"]),\n \"filter_ids\": filter_ids,\n \"passing_alert_id\": alert[\"candid\"],\n \"passed_at\": datetime.datetime.utcnow().strftime(\"%Y-%m-%dT%H:%M:%S.%f\"),\n \"origin\": \"Kowalski\",\n }\n if self.verbose > 1:\n log(alert_thin)\n\n with timer(\n f\"Posting metadata of {alert['objectId']} {alert['candid']} to SkyPortal\",\n self.verbose > 1,\n ):\n response = self.api_skyportal(\"POST\", \"/api/candidates\", alert_thin)\n if response.json()[\"status\"] == \"success\":\n log(f\"Posted {alert['objectId']} {alert['candid']} metadata to SkyPortal\")\n else:\n log(\n f\"Failed to post {alert['objectId']} {alert['candid']} metadata to SkyPortal\"\n )\n log(response.json())\n\n def alert_post_source(self, alert: Mapping, group_ids: Sequence):\n \"\"\"\n Save a ZTF alert as a source to groups on SkyPortal\n\n :param alert:\n :param group_ids:\n :return:\n \"\"\"\n # save source\n alert_thin = {\n \"id\": alert[\"objectId\"],\n \"group_ids\": group_ids,\n \"origin\": \"Kowalski\",\n }\n if self.verbose > 1:\n log(alert_thin)\n\n with timer(\n f\"Saving {alert['objectId']} {alert['candid']} as a Source on SkyPortal\",\n self.verbose > 1,\n ):\n response = self.api_skyportal(\"POST\", \"/api/sources\", alert_thin)\n if response.json()[\"status\"] == \"success\":\n log(f\"Saved {alert['objectId']} {alert['candid']} as a Source on SkyPortal\")\n else:\n log(\n f\"Failed to save {alert['objectId']} {alert['candid']} as a Source on SkyPortal\"\n )\n log(response.json())\n\n def alert_post_annotations(self, alert: Mapping, passed_filters: Sequence):\n \"\"\"\n Post annotations to SkyPortal for an alert that passed user-defined filters\n\n :param alert:\n :param passed_filters:\n :return:\n \"\"\"\n for passed_filter in passed_filters:\n annotations = {\n \"obj_id\": alert[\"objectId\"],\n \"origin\": f\"{passed_filter.get('group_name')}:{passed_filter.get('filter_name')}\",\n \"data\": passed_filter.get(\"data\", dict()).get(\"annotations\", dict()),\n \"group_ids\": [passed_filter.get(\"group_id\")],\n }\n if len(annotations[\"data\"]) > 0:\n with timer(\n f\"Posting annotation for {alert['objectId']} {alert['candid']} to SkyPortal\",\n self.verbose > 1,\n ):\n response = self.api_skyportal(\n \"POST\", \"/api/annotation\", annotations\n )\n if response.json()[\"status\"] == \"success\":\n log(f\"Posted {alert['objectId']} annotation to SkyPortal\")\n else:\n log(f\"Failed to post {alert['objectId']} annotation to SkyPortal\")\n log(response.json())\n\n def alert_put_annotations(self, alert: Mapping, passed_filters: Sequence):\n \"\"\"\n Update annotations on SkyPortal for an alert that passed user-defined filters\n\n :param alert:\n :param passed_filters:\n :return:\n \"\"\"\n # first need to learn existing annotation id's and corresponding author id's to use with the PUT call\n with timer(\n f\"Getting annotations for {alert['objectId']} from SkyPortal\",\n self.verbose > 1,\n ):\n response = self.api_skyportal(\n \"GET\", f\"/api/sources/{alert['objectId']}/annotations\"\n )\n if response.json()[\"status\"] == \"success\":\n log(f\"Got {alert['objectId']} annotations from SkyPortal\")\n else:\n log(f\"Failed to get {alert['objectId']} annotations from SkyPortal\")\n log(response.json())\n return False\n existing_annotations = {\n annotation[\"origin\"]: {\n \"annotation_id\": annotation[\"id\"],\n \"author_id\": annotation[\"author_id\"],\n }\n for annotation in response.json()[\"data\"]\n }\n\n for passed_filter in passed_filters:\n origin = (\n f\"{passed_filter.get('group_name')}:{passed_filter.get('filter_name')}\"\n )\n\n # no annotation exists on SkyPortal for this object? just post then\n if origin not in existing_annotations:\n self.alert_post_annotations(alert, [passed_filter])\n continue\n\n annotations = {\n \"author_id\": existing_annotations[origin][\"author_id\"],\n \"obj_id\": alert[\"objectId\"],\n \"origin\": origin,\n \"data\": passed_filter.get(\"data\", dict()).get(\"annotations\", dict()),\n \"group_ids\": [passed_filter.get(\"group_id\")],\n }\n if len(annotations[\"data\"]) > 0 and passed_filter.get(\n \"update_annotations\", False\n ):\n with timer(\n f\"Putting annotation for {alert['objectId']} {alert['candid']} to SkyPortal\",\n self.verbose > 1,\n ):\n response = self.api_skyportal(\n \"PUT\",\n f\"/api/annotation/{existing_annotations[origin]['annotation_id']}\",\n annotations,\n )\n if response.json()[\"status\"] == \"success\":\n log(f\"Posted {alert['objectId']} annotation to SkyPortal\")\n else:\n log(f\"Failed to post {alert['objectId']} annotation to SkyPortal\")\n log(response.json())\n\n def alert_post_thumbnails(self, alert: Mapping):\n \"\"\"\n Post ZTF alert thumbnails to SkyPortal\n\n :param alert:\n :return:\n \"\"\"\n for ttype, ztftype in [\n (\"new\", \"Science\"),\n (\"ref\", \"Template\"),\n (\"sub\", \"Difference\"),\n ]:\n with timer(\n f\"Making {ztftype} thumbnail for {alert['objectId']} {alert['candid']}\",\n self.verbose > 1,\n ):\n thumb = make_thumbnail(alert, ttype, ztftype)\n\n with timer(\n f\"Posting {ztftype} thumbnail for {alert['objectId']} {alert['candid']} to SkyPortal\",\n self.verbose > 1,\n ):\n response = self.api_skyportal(\"POST\", \"/api/thumbnail\", thumb)\n\n if response.json()[\"status\"] == \"success\":\n log(\n f\"Posted {alert['objectId']} {alert['candid']} {ztftype} cutout to SkyPortal\"\n )\n else:\n log(\n f\"Failed to post {alert['objectId']} {alert['candid']} {ztftype} cutout to SkyPortal\"\n )\n log(response.json())\n\n def alert_put_photometry(self, alert):\n \"\"\"PUT photometry to SkyPortal\n\n :param alert:\n :return:\n \"\"\"\n with timer(\n f\"Making alert photometry of {alert['objectId']} {alert['candid']}\",\n self.verbose > 1,\n ):\n df_photometry = make_photometry(alert)\n\n df_photometry[\"stream_id\"] = df_photometry[\"programid\"].apply(\n lambda programid: self.ztf_program_id_to_stream_id[programid]\n )\n\n # post photometry by stream_id\n for stream_id in set(df_photometry.stream_id.unique()):\n stream_id_mask = df_photometry.stream_id == int(stream_id)\n photometry = {\n \"obj_id\": alert[\"objectId\"],\n \"stream_ids\": [int(stream_id)],\n \"instrument_id\": self.instrument_id,\n \"mjd\": df_photometry.loc[stream_id_mask, \"mjd\"].tolist(),\n \"flux\": df_photometry.loc[stream_id_mask, \"flux\"].tolist(),\n \"fluxerr\": df_photometry.loc[stream_id_mask, \"fluxerr\"].tolist(),\n \"zp\": df_photometry.loc[stream_id_mask, \"zp\"].tolist(),\n \"magsys\": df_photometry.loc[stream_id_mask, \"zpsys\"].tolist(),\n \"filter\": df_photometry.loc[stream_id_mask, \"ztf_filter\"].tolist(),\n \"ra\": df_photometry.loc[stream_id_mask, \"ra\"].tolist(),\n \"dec\": df_photometry.loc[stream_id_mask, \"dec\"].tolist(),\n }\n\n if (len(photometry.get(\"flux\", ())) > 0) or (\n len(photometry.get(\"fluxerr\", ())) > 0\n ):\n with timer(\n f\"Posting photometry of {alert['objectId']} {alert['candid']}, \"\n f\"stream_id={stream_id} to SkyPortal\",\n self.verbose > 1,\n ):\n response = self.api_skyportal(\"PUT\", \"/api/photometry\", photometry)\n if response.json()[\"status\"] == \"success\":\n log(\n f\"Posted {alert['objectId']} photometry stream_id={stream_id} to SkyPortal\"\n )\n else:\n log(\n f\"Failed to post {alert['objectId']} photometry stream_id={stream_id} to SkyPortal\"\n )\n log(response.json())\n\n def alert_sentinel_skyportal(self, alert, prv_candidates, passed_filters):\n \"\"\"\n Post alerts to SkyPortal, if need be.\n\n Logic:\n - check if candidate/source exist on SP\n - if candidate does not exist and len(passed_filters) > 0\n - post metadata with all filter_ids in single call to /api/candidates\n - post full light curve with all group_ids in single call to /api/photometry\n - post thumbnails\n - if candidate exists:\n - get filter_ids of saved candidate from SP\n - post to /api/candidates with new_filter_ids, if any\n - post alert light curve in single PUT call to /api/photometry specifying stream_ids\n - if source exists:\n - get groups and check stream access\n - decide which points to post to what groups based on permissions\n - post alert light curve in single PUT call to /api/photometry specifying stream_ids\n\n :param alert: ZTF_alert with a stripped-off prv_candidates section\n :param prv_candidates: could be plain prv_candidates section of an alert, or extended alert history\n :param passed_filters: list of filters that alert passed, with their output\n :return:\n \"\"\"\n # check if candidate/source exist in SP:\n with timer(\n f\"Checking if {alert['objectId']} is Candidate in SkyPortal\",\n self.verbose > 1,\n ):\n response = self.api_skyportal(\n \"HEAD\", f\"/api/candidates/{alert['objectId']}\"\n )\n is_candidate = response.status_code == 200\n if self.verbose > 1:\n log(\n f\"{alert['objectId']} {'is' if is_candidate else 'is not'} Candidate in SkyPortal\"\n )\n with timer(\n f\"Checking if {alert['objectId']} is Source in SkyPortal\", self.verbose > 1\n ):\n response = self.api_skyportal(\"HEAD\", f\"/api/sources/{alert['objectId']}\")\n is_source = response.status_code == 200\n if self.verbose > 1:\n log(\n f\"{alert['objectId']} {'is' if is_source else 'is not'} Source in SkyPortal\"\n )\n\n # obj does not exit in SP:\n if (not is_candidate) and (not is_source):\n # passed at least one filter?\n if len(passed_filters) > 0:\n # post candidate\n filter_ids = [f.get(\"filter_id\") for f in passed_filters]\n self.alert_post_candidate(alert, filter_ids)\n\n # post annotations\n self.alert_post_annotations(alert, passed_filters)\n\n # post full light curve\n try:\n alert[\"prv_candidates\"] = list(\n self.mongo.db[self.collection_alerts_aux].find(\n {\"_id\": alert[\"objectId\"]}, {\"prv_candidates\": 1}, limit=1\n )\n )[0][\"prv_candidates\"]\n except Exception as e:\n # this should never happen, but just in case\n log(e)\n alert[\"prv_candidates\"] = prv_candidates\n\n self.alert_put_photometry(alert)\n\n # post thumbnails\n self.alert_post_thumbnails(alert)\n\n # post source if autosave=True\n autosave_group_ids = [\n f.get(\"group_id\")\n for f in passed_filters\n if f.get(\"autosave\", False)\n ]\n if len(autosave_group_ids) > 0:\n self.alert_post_source(alert, autosave_group_ids)\n\n # obj exists in SP:\n else:\n if len(passed_filters) > 0:\n filter_ids = [f.get(\"filter_id\") for f in passed_filters]\n\n # post candidate with new filter ids\n self.alert_post_candidate(alert, filter_ids)\n\n # put annotations\n self.alert_put_annotations(alert, passed_filters)\n\n # already saved as a source?\n if is_source:\n # get info on the corresponding groups:\n with timer(\n f\"Getting source groups info on {alert['objectId']} from SkyPortal\",\n self.verbose > 1,\n ):\n response = self.api_skyportal(\n \"GET\", f\"/api/sources/{alert['objectId']}/groups\"\n )\n if response.json()[\"status\"] == \"success\":\n existing_groups = response.json()[\"data\"]\n existing_group_ids = [g[\"id\"] for g in existing_groups]\n\n # post source if autosave=True and not already saved\n autosave_group_ids = [\n f.get(\"group_id\")\n for f in passed_filters\n if f.get(\"autosave\", False)\n and (f.get(\"group_id\") not in existing_group_ids)\n ]\n if len(autosave_group_ids) > 0:\n self.alert_post_source(alert, autosave_group_ids)\n else:\n log(f\"Failed to get source groups info on {alert['objectId']}\")\n else:\n # post source if autosave=True and not is_source\n autosave_group_ids = [\n f.get(\"group_id\")\n for f in passed_filters\n if f.get(\"autosave\", False)\n ]\n if len(autosave_group_ids) > 0:\n self.alert_post_source(alert, autosave_group_ids)\n\n # post alert photometry in single call to /api/photometry\n alert[\"prv_candidates\"] = prv_candidates\n\n self.alert_put_photometry(alert)\n\n\nclass WorkerInitializer(dask.distributed.WorkerPlugin):\n def __init__(self, *args, **kwargs):\n self.alert_worker = None\n\n def setup(self, worker: dask.distributed.Worker):\n self.alert_worker = AlertWorker()\n\n\ndef topic_listener(\n topic,\n bootstrap_servers: str,\n offset_reset: str = \"earliest\",\n group: str = None,\n test: bool = False,\n):\n \"\"\"\n Listen to a topic\n :param topic:\n :param bootstrap_servers:\n :param offset_reset:\n :param group:\n :param test: when testing, terminate once reached end of partition\n :return:\n \"\"\"\n\n # Configure dask client\n dask_client = dask.distributed.Client(\n address=f\"{config['dask']['host']}:{config['dask']['scheduler_port']}\"\n )\n\n # init each worker with AlertWorker instance\n worker_initializer = WorkerInitializer()\n dask_client.register_worker_plugin(worker_initializer, name=\"worker-init\")\n\n # Configure consumer connection to Kafka broker\n conf = {\n \"bootstrap.servers\": bootstrap_servers,\n \"default.topic.config\": {\"auto.offset.reset\": offset_reset},\n }\n if group is not None:\n conf[\"group.id\"] = group\n else:\n conf[\"group.id\"] = os.environ.get(\"HOSTNAME\", \"kowalski\")\n\n # make it unique:\n conf[\n \"group.id\"\n ] = f\"{conf['group.id']}_{datetime.datetime.utcnow().strftime('%Y-%m-%d_%H:%M:%S.%f')}\"\n\n # Start alert stream consumer\n stream_reader = AlertConsumer(topic, dask_client, **conf)\n\n while True:\n try:\n # poll!\n stream_reader.poll()\n\n except EopError as e:\n # Write when reaching end of partition\n log(e.message)\n if test:\n # when testing, terminate once reached end of partition:\n sys.exit()\n except IndexError:\n log(\"Data cannot be decoded\\n\")\n except UnicodeDecodeError:\n log(\"Unexpected data format received\\n\")\n except KeyboardInterrupt:\n log(\"Aborted by user\\n\")\n sys.exit()\n except Exception as e:\n log(str(e))\n _err = traceback.format_exc()\n log(_err)\n sys.exit()\n\n\ndef watchdog(obs_date: str = None, test: bool = False):\n \"\"\"\n Watchdog for topic listeners\n\n :param obs_date: observing date: YYYYMMDD\n :param test: test mode\n :return:\n \"\"\"\n\n init_db_sync(config=config, verbose=True)\n\n topics_on_watch = dict()\n\n while True:\n\n try:\n # get kafka topic names with kafka-topics command\n if not test:\n # Production Kafka stream at IPAC\n kafka_cmd = [\n os.path.join(config[\"path\"][\"kafka\"], \"bin\", \"kafka-topics.sh\"),\n \"--zookeeper\",\n config[\"kafka\"][\"zookeeper\"],\n \"-list\",\n ]\n else:\n # Local test stream\n kafka_cmd = [\n os.path.join(config[\"path\"][\"kafka\"], \"bin\", \"kafka-topics.sh\"),\n \"--zookeeper\",\n config[\"kafka\"][\"zookeeper.test\"],\n \"-list\",\n ]\n\n topics = (\n subprocess.run(kafka_cmd, stdout=subprocess.PIPE)\n .stdout.decode(\"utf-8\")\n .split(\"\\n\")[:-1]\n )\n\n if obs_date is None:\n datestr = datetime.datetime.utcnow().strftime(\"%Y%m%d\")\n else:\n datestr = obs_date\n # as of 20180403, the naming convention is ztf_%Y%m%d_programidN\n # exclude ZUDS, ingest separately\n topics_tonight = [\n t\n for t in topics\n if (datestr in t) and (\"programid\" in t) and (\"zuds\" not in t)\n ]\n log(f\"Topics: {topics_tonight}\")\n\n for t in topics_tonight:\n if t not in topics_on_watch:\n log(f\"Starting listener thread for {t}\")\n offset_reset = config[\"kafka\"][\"default.topic.config\"][\n \"auto.offset.reset\"\n ]\n if not test:\n bootstrap_servers = config[\"kafka\"][\"bootstrap.servers\"]\n else:\n bootstrap_servers = config[\"kafka\"][\"bootstrap.test.servers\"]\n group = config[\"kafka\"][\"group\"]\n\n topics_on_watch[t] = multiprocessing.Process(\n target=topic_listener,\n args=(t, bootstrap_servers, offset_reset, group, test),\n )\n topics_on_watch[t].daemon = True\n topics_on_watch[t].start()\n\n else:\n log(f\"Performing thread health check for {t}\")\n try:\n if not topics_on_watch[t].is_alive():\n log(f\"Thread {t} died, removing\")\n # topics_on_watch[t].terminate()\n topics_on_watch.pop(t, None)\n else:\n log(f\"Thread {t} appears normal\")\n except Exception as _e:\n log(f\"Failed to perform health check: {_e}\")\n pass\n\n if test:\n time.sleep(120)\n # when testing, wait for topic listeners to pull all the data, then break\n # fixme: do this more gracefully\n for t in topics_on_watch:\n topics_on_watch[t].kill()\n break\n\n except Exception as e:\n log(str(e))\n _err = traceback.format_exc()\n log(str(_err))\n\n time.sleep(60)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Kowalski's ZTF Alert Broker\")\n parser.add_argument(\"--obsdate\", help=\"observing date YYYYMMDD\")\n parser.add_argument(\"--test\", help=\"listen to the test stream\", action=\"store_true\")\n\n args = parser.parse_args()\n\n watchdog(obs_date=args.obsdate, test=args.test)\n"
] | [
[
"numpy.log",
"numpy.nan_to_num",
"numpy.float64",
"numpy.isfinite",
"matplotlib.pyplot.figure",
"tensorflow.config.optimizer.set_jit",
"matplotlib.pyplot.savefig",
"numpy.abs",
"numpy.expand_dims",
"numpy.isnan",
"numpy.zeros",
"numpy.float32",
"pandas.concat",
"matplotlib.pyplot.close",
"numpy.pad",
"numpy.linalg.norm",
"numpy.rint",
"matplotlib.pyplot.Axes",
"numpy.flipud",
"tensorflow.keras.models.load_model",
"pandas.DataFrame",
"numpy.array"
]
] |
eliaskousk/FATE | [
"242e47d6ae439a3b69ecb1610cb370b29b024413"
] | [
"python/federatedml/ensemble/test/gh_packing_compressing_test.py"
] | [
"#\n# Copyright 2019 The FATE 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\nimport unittest\nimport functools\nimport math\nfrom fate_arch.session import computing_session as session\nfrom federatedml.ensemble.basic_algorithms.decision_tree.tree_core.g_h_optim import PackedGHCompressor, GHPacker, fix_point_precision\nfrom federatedml.secureprotol.encrypt import PaillierEncrypt, FakeEncrypt\nfrom federatedml.ensemble.basic_algorithms.decision_tree.tree_core.splitter import SplitInfo\nfrom federatedml.secureprotol.encrypt_mode import EncryptModeCalculator\nfrom federatedml.util import consts\nimport numpy as np\n\n\nnp.random.seed(114514)\n\n\ndef generate_bin_gh(num):\n # (-1, 1)\n g = np.random.random(num)\n h = np.random.random(num)\n g = g*2 - 1\n return g, h\n\n\ndef generate_reg_gh(num, lower, upper):\n g = np.random.random(num)\n h = np.zeros(num) + 2\n g = g * (upper - lower) + lower\n return g, h\n\n\ndef cmp(a, b):\n if a[0] > b[0]:\n return 1\n else:\n return -1\n\n\ndef en_gh_list(g, h, en):\n en_g = [en.encrypt(i) for i in g]\n en_h = [en.encrypt(i) for i in h]\n return en_g, en_h\n\n\ndef truncate(f, n=consts.TREE_DECIMAL_ROUND):\n return math.floor(f * 10 ** n) / 10 ** n\n\n\ndef make_random_sum(collected_gh, g, h, en_g_l, en_h_l, max_sample_num):\n\n selected_sample_num = np.random.randint(max_sample_num) + 1# at least 1 sample\n\n idx = np.random.random(selected_sample_num)\n idx = np.unique((idx * max_sample_num).astype(int))\n print('randomly select {} samples'.format(len(idx)))\n selected_g = g[idx]\n selected_h = h[idx]\n g_sum = selected_g.sum()\n h_sum = selected_h.sum()\n g_h_list = sorted(collected_gh, key=functools.cmp_to_key(cmp))\n sum_gh = 0\n en_g_sum = 0\n en_h_sum = 0\n for i in idx:\n gh = g_h_list[i][1][0]\n\n sum_gh += gh\n en_g_sum += en_g_l[i]\n en_h_sum += en_h_l[i]\n\n return g_sum, h_sum, sum_gh, en_g_sum, en_h_sum, len(idx)\n\n\nclass TestFeatureHistogram(unittest.TestCase):\n\n @staticmethod\n def prepare_testing_data(g, h, en, max_sample_num, sample_id, task_type, g_min=None, g_max=None):\n\n calculator = EncryptModeCalculator(encrypter=en)\n packer = GHPacker(max_sample_num, en_calculator=calculator, sync_para=False, task_type=task_type,\n g_min=g_min, g_max=g_max)\n en_g_l, en_h_l = en_gh_list(g, h, en)\n data_list = [(id_, (g_, h_)) for id_, g_, h_ in zip(sample_id, g, h)]\n data_table = session.parallelize(data_list, 4, include_key=True)\n en_table = packer.pack_and_encrypt(data_table)\n collected_gh = list(en_table.collect())\n\n return packer, en_g_l, en_h_l, en_table, collected_gh\n\n @classmethod\n def setUpClass(cls):\n\n session.init(\"test_gh_packing\")\n\n cls.max_sample_num = 1000\n cls.test_num = 10\n cls.split_info_test_num = 200\n\n key_length = 1024\n sample_id = [i for i in range(cls.max_sample_num)]\n\n # classification data\n cls.g, cls.h = generate_bin_gh(cls.max_sample_num)\n\n cls.p_en = PaillierEncrypt()\n cls.p_en.generate_key(key_length)\n\n cls.p_packer, cls.p_en_g_l, cls.p_en_h_l, cls.p_en_table, cls.p_collected_gh = \\\n cls.prepare_testing_data(cls.g, cls.h, cls.p_en, cls.max_sample_num, sample_id, consts.CLASSIFICATION)\n cls.compressor = PackedGHCompressor(sync_para=False)\n cls.compressor.compressor._padding_length, cls.compressor.compressor._capacity = \\\n cls.p_packer.packer.cipher_compress_suggest()\n print('paillier compress para {}'.format(cls.p_packer.packer.cipher_compress_suggest()))\n\n # regression data\n cls.g_reg, cls.h_reg = generate_reg_gh(cls.max_sample_num, -1000, 1000)\n cls.reg_p_packer, cls.reg_p_en_g_l, cls.reg_p_en_h_l, cls.reg_p_en_table, cls.reg_p_collected_gh = \\\n cls.prepare_testing_data(cls.g_reg, cls.h_reg, cls.p_en, cls.max_sample_num, sample_id, consts.REGRESSION,\n g_min=-1000, g_max=1000)\n cls.reg_compressor = PackedGHCompressor(sync_para=False)\n cls.reg_compressor.compressor._padding_length, cls.reg_compressor.compressor._capacity = \\\n cls.reg_p_packer.packer.cipher_compress_suggest()\n print('paillier compress para {}'.format(cls.p_packer.packer.cipher_compress_suggest()))\n\n print('initialization done')\n\n def run_gh_accumulate_test(self, test_num, collected_gh, en_g_l, en_h_l, packer, en, g, h, check=True):\n\n print('{} test to run'.format(test_num))\n for i in range(test_num):\n print('executing test {}'.format(i))\n g_sum, h_sum, en_sum, en_g_sum, en_h_sum, sample_num = make_random_sum(collected_gh, g, h,\n en_g_l,\n en_h_l,\n self.max_sample_num)\n de_num = en.raw_decrypt(en_sum)\n unpack_num = packer.packer._unpack_an_int(de_num, packer.packer._bit_assignment[0])\n\n g_sum_ = unpack_num[0] / fix_point_precision - sample_num * packer.g_offset\n h_sum_ = unpack_num[1] / fix_point_precision\n\n g_sum_2 = en.decrypt(en_g_sum)\n h_sum_2 = en.decrypt(en_h_sum)\n\n print(g_sum, h_sum)\n print(g_sum_2, h_sum_2)\n print(g_sum_, h_sum_)\n\n g_sum, h_sum = truncate(g_sum), truncate(h_sum)\n g_sum_, h_sum_ = truncate(g_sum_), truncate(h_sum_)\n g_sum_2, h_sum_2 = truncate(g_sum_2), truncate(h_sum_2)\n\n print(g_sum, h_sum)\n print(g_sum_2, h_sum_2)\n print(g_sum_, h_sum_)\n\n if check:\n # make sure packing result close to plaintext sum\n self.assertTrue(g_sum_ == g_sum)\n self.assertTrue(h_sum_ == h_sum)\n\n print('passed')\n\n def test_pack_gh_accumulate(self):\n\n # test the correctness of gh packing(in comparision to plaintext)\n\n # Paillier\n self.run_gh_accumulate_test(self.test_num, self.p_collected_gh, self.p_en_g_l, self.p_en_h_l, self.p_packer,\n self.p_en, self.g, self.h)\n\n print('*'*30)\n print('test paillier done')\n print('*'*30)\n\n def test_split_info_cipher_compress(self):\n\n # test the correctness of cipher compressing\n print('testing binary')\n collected_gh = self.p_collected_gh\n en_g_l = self.p_en_g_l\n en_h_l = self.p_en_h_l\n packer = self.p_packer\n en = self.p_en\n\n sp_list = []\n g_sum_list, h_sum_list = [], []\n pack_en_list = []\n\n for i in range(self.split_info_test_num):\n g_sum, h_sum, en_sum, en_g_sum, en_h_sum, sample_num = make_random_sum(collected_gh, self.g, self.h,\n en_g_l,\n en_h_l,\n self.max_sample_num)\n sp = SplitInfo(sum_grad=en_sum, sum_hess=0, sample_count=sample_num)\n sp_list.append(sp)\n g_sum_list.append(g_sum)\n h_sum_list.append(h_sum)\n pack_en_list.append(en_sum)\n\n print('generating split-info done')\n packages = self.compressor.compress_split_info(sp_list[:-1], sp_list[-1])\n print('package length is {}'.format(len(packages)))\n unpack_rs = packer.decompress_and_unpack(packages)\n case_id = 0\n for s, g, h, en_gh in zip(unpack_rs, g_sum_list, h_sum_list, pack_en_list):\n print('*'*10)\n print(case_id)\n case_id += 1\n de_num = en.raw_decrypt(en_gh)\n unpack_num = packer.packer._unpack_an_int(de_num, packer.packer._bit_assignment[0])\n g_sum_ = unpack_num[0] / fix_point_precision - s.sample_count * packer.g_offset\n h_sum_ = unpack_num[1] / fix_point_precision\n\n print(s.sample_count)\n print(s.sum_grad, g_sum_, g)\n print(s.sum_hess, h_sum_, h)\n\n # make sure cipher compress is correct\n self.assertTrue(truncate(s.sum_grad) == truncate(g_sum_))\n self.assertTrue(truncate(s.sum_hess) == truncate(h_sum_))\n print('check passed')\n\n def test_regression_cipher_compress(self):\n\n # test the correctness of cipher compressing\n print('testing regression')\n collected_gh = self.reg_p_collected_gh\n en_g_l = self.reg_p_en_g_l\n en_h_l = self.reg_p_en_h_l\n packer = self.reg_p_packer\n en = self.p_en\n\n sp_list = []\n g_sum_list, h_sum_list = [], []\n pack_en_list = []\n\n for i in range(self.split_info_test_num):\n g_sum, h_sum, en_sum, en_g_sum, en_h_sum, sample_num = make_random_sum(collected_gh, self.g_reg, self.h_reg,\n en_g_l,\n en_h_l,\n self.max_sample_num)\n sp = SplitInfo(sum_grad=en_sum, sum_hess=0, sample_count=sample_num)\n sp_list.append(sp)\n g_sum_list.append(g_sum)\n h_sum_list.append(h_sum)\n pack_en_list.append(en_sum)\n\n print('generating split-info done')\n packages = self.reg_compressor.compress_split_info(sp_list[:-1], sp_list[-1])\n print('package length is {}'.format(len(packages)))\n unpack_rs = packer.decompress_and_unpack(packages)\n case_id = 0\n for s, g, h, en_gh in zip(unpack_rs, g_sum_list, h_sum_list, pack_en_list):\n print('*' * 10)\n print(case_id)\n case_id += 1\n de_num = en.raw_decrypt(en_gh) # make sure packing result close to plaintext sum\n unpack_num = packer.packer._unpack_an_int(de_num, packer.packer._bit_assignment[0])\n g_sum_ = unpack_num[0] / fix_point_precision - s.sample_count * packer.g_offset\n h_sum_ = unpack_num[1] / fix_point_precision\n\n print(s.sample_count)\n print(s.sum_grad, g_sum_, g)\n print(s.sum_hess, h_sum_, h)\n\n # make sure cipher compress is correct\n self.assertTrue(truncate(s.sum_grad) == truncate(g_sum_))\n self.assertTrue(truncate(s.sum_hess) == truncate(h_sum_))\n print('check passed')\n\n def test_regression_gh_packing(self):\n\n # Paillier\n self.run_gh_accumulate_test(self.test_num, self.reg_p_collected_gh, self.reg_p_en_g_l, self.reg_p_en_h_l, self.reg_p_packer,\n self.p_en, self.g_reg, self.h_reg, check=False) # float error in regression is not controllable\n\n @classmethod\n def tearDownClass(self):\n session.stop()\n\n\nif __name__ == '__main__':\n\n unittest.main()\n\n"
] | [
[
"numpy.random.random",
"numpy.random.randint",
"numpy.random.seed",
"numpy.zeros"
]
] |
center3d/MLW | [
"192cc991df61bd8991a51702a53df6a09448d4f7"
] | [
"zmk/nyokaserver/nyokaUtilities.py"
] | [
"# nyokaUtilities.py\nimport numpy as np\nfrom random import choice\nfrom string import ascii_uppercase\nimport copy,json\nimport ast,pathlib\nimport traceback\nfrom nyoka import PMML43Ext as ny\nglobal MEMORY_DICT_ARCHITECTURE,MEMORY_OF_LAYERS\n\nsettingFilePath='./settingFiles/'\nsavedModels='./SavedModels/'\nMEMORY_OF_LAYERS={}\nfrom trainModel.mergeTrainingV2 import PMMLMODELSTORAGE\nlayerDetail=open(settingFilePath+'listOflayers.json','r')\nMEMORY_OF_LAYERS=json.loads(layerDetail.read())\n#########################################All functions is to write PMML###############################\nclass NyokaUtilities:\n\n def convertToStandardJson(self,pp):\n tempData={}\n tempData['connectionLayerId']=pp['connectionLayerId']\n tempData['itemType']=pp['itemType']\n tempData['layerType']=pp['layerType']\n tempData['connectionLayerId']=pp['connectionLayerId']\n tempData['layerId']=pp['layerId']\n tempData['name']=pp['name']\n tempData['properties']={}\n for j in pp['properties']:\n tempData['properties'][j['id']]=j['value']\n return tempData\n\n\n def calculateOutputSize(self,N,S,F,P=None):\n if P==None:\n P=0\n val=((N-F+(2*P))/S)+1\n return int(val)\n\n def calculatePadding(self,N,O,S,F):\n val=abs((N-(O*S)-F+S)/2)\n return int(val)\n\n def outputForDepthWiseConv2D(self,tempData):\n try:\n tempData=self.convertToStandardJson(tempData)\n wid,heig,channel=tempData['properties']['inputDimension']\n widFil,heigFil=tempData['properties']['kernel']\n widStri,heigStri=tempData['properties']['stride']\n if tempData['properties']['paddingType']=='valid':\n padding=0\n widthOutput=self.calculateOutputSize(wid,widStri,widFil,padding)\n heightOutput=self.calculateOutputSize(heig,heigStri,heigFil,padding)\n elif tempData['properties']['paddingType']=='same':\n padding=self.calculatePadding(wid,wid,widStri,widFil)\n widthOutput=self.calculateOutputSize(wid,widStri,widFil,padding)\n heightOutput=self.calculateOutputSize(heig,heigStri,heigFil,padding)\n out_filter=channel*tempData['properties']['depthMultiplier']\n return((widthOutput,heightOutput,out_filter),'success','success')\n except Exception as e:\n errorMessage='Error while calculating output >> '+ str(e)\n errorTraceback=str(traceback.format_exc())\n wid,heig,out_filter=(0,0,0)\n return((wid,heig,out_filter),errorMessage,errorTraceback)\n\n\n def outputForConv2D(self,tempData2):\n try:\n tempData2=self.convertToStandardJson(tempData2)\n wid,heig,channel=tempData2['properties']['inputDimension']\n widFil,heigFil=tempData2['properties']['kernel']\n widStri,heigStri=tempData2['properties']['stride']\n try:\n featureMaps=tempData2['properties']['featureMaps']\n except:\n featureMaps=None\n if tempData2['properties']['paddingType']=='valid':\n padding=0\n widthOutput=self.calculateOutputSize(wid,widStri,widFil,padding)\n heightOutput=self.calculateOutputSize(heig,heigStri,heigFil,padding)\n elif tempData2['properties']['paddingType']=='same':\n padding=self.calculatePadding(wid,heig,widStri,widFil)\n widthOutput=self.calculateOutputSize(wid,widStri,widFil,padding)\n heightOutput=self.calculateOutputSize(heig,heigStri,heigFil,padding)\n if featureMaps==None:\n return ((widthOutput,heightOutput,channel), 'success','success')\n else:\n return ((widthOutput,heightOutput,featureMaps), 'success','success')\n except Exception as e:\n # print('No input came')\n errorMessage='Error while calculating output >> '+ str(e)\n errorTraceback=str(traceback.format_exc())\n widthOutput,heightOutput,featureMaps=0,0,0\n return ((widthOutput,heightOutput,featureMaps), errorMessage,errorTraceback)\n\n\n def outputForMaxPooling1D(self,tempData):\n try:\n tempData=self.convertToStandardJson(tempData)\n N = tempData['properties']['inputDimension'][-2]\n S = tempData['properties']['stride']\n F = tempData['properties']['poolSize']\n return ((self.calculateOutputSize(N, S, F), tempData['properties']['inputDimension'][-1]), 'success','success')\n except Exception as e:\n # print('No input came')\n errorMessage='Error while calculating output >> '+ str(e)\n errorTraceback=str(traceback.format_exc())\n return ((0,0), errorMessage,errorTraceback)\n\n\n def outputForMaxPooling2D(self,tempData):\n # print('>>>>>> outputForMaxpooling1D', tempData)\n try:\n tempData=self.convertToStandardJson(tempData)\n N1, N2 = tempData['properties']['inputDimension'][:-1]\n if len(tempData['properties']['stride']) == 1:\n S1 = tempData['properties']['stride'][0]\n else:\n S1, S2 = tempData['properties']['stride']\n if len(tempData['properties']['poolSize']) == 1:\n F1 = tempData['properties']['poolSize'][0]\n else:\n F1, F2 = tempData['properties']['poolSize']\n return ((self.calculateOutputSize(N1, S1, F1), self.calculateOutputSize(N2, S1, F1), \\\n tempData['properties']['inputDimension'][-1]), 'success','success')\n except Exception as e:\n # print('No input came')\n errorMessage='Error while calculating output >> '+ str(e)\n errorTraceback=str(traceback.format_exc())\n return ((0,0,0),errorMessage,errorTraceback)\n\n\n def outputForInput(self,inputDimension):\n # print ('$$$$$$$$$$$$$outputForInput >>>>>> ',inputDimension)\n inputDimension=self.convertToStandardJson(inputDimension)\n if len(inputDimension['properties']['inputDimension'])==1:\n return ((inputDimension['properties']['inputDimension'][0],1),'success','success')\n else:\n return ((inputDimension['properties']['inputDimension']),'success','success')\n\n\n def outputForFlatten(self,tempData4):\n try:\n tempData4=self.convertToStandardJson(tempData4)\n tomul=tempData4['properties']['inputDimension']\n val=int(np.prod(tomul))\n return ((val,1), 'success','success')\n except Exception as e:\n # print('No input came')\n errorMessage='Error while calculating output >> '+ str(e)\n errorTraceback=str(traceback.format_exc())\n return ((0,0), errorMessage,errorTraceback)\n\n\n def outputFor1DPadding(self,tempData):\n try:\n tempData=self.convertToStandardJson(tempData)\n width,height=tempData['properties']['inputDimension']\n if len(tempData['properties']['paddingDims']) == 1:\n left_pad = right_pad = tempData['properties']['paddingDims'][0]\n else:\n left_pad, right_pad=tempData['properties']['paddingDims']\n width=width+left_pad+right_pad\n return ((width, height),'success','success')\n except Exception as e:\n # print('No input came')\n errorMessage='Error while calculating output >> '+ str(e)\n errorTraceback=str(traceback.format_exc())\n return ((0,0), errorMessage,errorTraceback)\n\n\n def outputFor2DPadding(self,tempData6):\n try:\n tempData6=self.convertToStandardJson(tempData6)\n width,height,channel=tempData6['properties']['inputDimension']\n if len(tempData6['properties']['paddingDims']) == 1:\n top_pad = bottom_pad = left_pad = right_pad = tempData6['properties']['paddingDims'][0]\n elif len(tempData6['properties']['paddingDims']) == 2:\n top_pad, left_pad=tempData6['properties']['paddingDims']\n bottom_pad, right_pad = top_pad, left_pad\n else:\n top_pad, bottom_pad,left_pad, right_pad=tempData6['properties']['paddingDims']\n width=width+left_pad+right_pad\n height=height+top_pad+bottom_pad\n return ((width,height,channel), 'success','success')\n except Exception as e:\n # print('No input came')\n errorMessage='Error while calculating output >> '+ str(e)\n errorTraceback=str(traceback.format_exc())\n return ((0,0,0), errorMessage,errorTraceback)\n\n\n def outputForDense(self,tempdata7):\n try:\n tempdata7=self.convertToStandardJson(tempdata7)\n tomul=tempdata7['properties']['units']\n if tomul.__class__.__name__ != 'int':\n raise Exception(\"Expected integer value for units, got string/empty value\",tomul)\n return ((tomul,1),'success','success')\n except Exception as e :\n errorMessage='Error while calculating output >> '+ str(e)\n errorTraceback=str(traceback.format_exc())\n # print('No input came>>', errorMessage)\n tomul=0\n return ((tomul,1),errorMessage,errorTraceback)\n\n\n def outputForGlobalAverage2D(self,tempdata7):\n try:\n tempdata7=self.convertToStandardJson(tempdata7)\n tomul=tempdata7['properties']['inputDimension'][2]\n return ((1,1,tomul), 'success','success')\n except Exception as e :\n errorMessage='Error while calculating output >> '+ str(e)\n errorTraceback=str(traceback.format_exc())\n # print('No input came')\n tomul=0\n return ((0,0,0),errorMessage,errorTraceback) \n\n def outputForReshape(self,tempdata7):\n try:\n # print('>>>>>>>>Reshape', tempdata7)\n tempdata7=self.convertToStandardJson(tempdata7)\n return (tempdata7['properties']['reshapeTarget'],'success','success')\n except Exception as e :\n errorMessage='Error while calculating output >> '+ str(e)\n errorTraceback=str(traceback.format_exc())\n # print('No input came')\n return ((0,0,0),errorMessage,errorTraceback)\n\n\n def selectArchitecture(self,checkTemplateID):\n if checkTemplateID=='mobilenetArch':\n pmmlObj = ny.parse(open(settingFilePath+'MobilenetArch.pmml','r'), silence=True)\n templateArch=self.pmmlToJson(settingFilePath+'MobilenetArch.pmml')\n elif checkTemplateID=='vgg16Arch':\n pmmlObj = ny.parse(open(settingFilePath+'vGG16Arch.pmml','r'), silence=True)\n templateArch=self.pmmlToJson(settingFilePath+'vGG16Arch.pmml')\n elif checkTemplateID=='vgg19Arch':\n pmmlObj = ny.parse(open(settingFilePath+'vGG19Arch.pmml','r'), silence=True)\n templateArch=self.pmmlToJson(settingFilePath+'vGG19Arch.pmml')\n return templateArch,pmmlObj\n\n\n def addLayertoJson(self,tempData):\n if tempData['layerType'] in ['Input']:\n valRet,messageInfo,traceBack=self.outputForInput(tempData)\n [j for j in tempData['properties'] if j['id']=='outputDimension' ][0]['value']=valRet\n [j for j in tempData['properties'] if j['id']=='inputDimension' ][0]['value']=valRet\n elif tempData['layerType'] in ['Reshape']:\n valRet,messageInfo,traceBack=self.outputForReshape(tempData)\n [j for j in tempData['properties'] if j['id']=='outputDimension' ][0]['value']=valRet\n elif tempData['layerType'] in ['Activation','Dropout']:\n # print ('$$$$$$$$$$$$$ Activation',tempData)\n valRet,messageInfo,traceBack=self.outputForInput(tempData)\n [j for j in tempData['properties'] if j['id']=='outputDimension' ][0]['value']=valRet\n elif tempData['layerType'] in ['BatchNormalization']:\n valRet,messageInfo,traceBack=self.outputForInput(tempData)\n [j for j in tempData['properties'] if j['id']=='outputDimension' ][0]['value']=valRet\n elif tempData['layerType'] in ['Conv2D']:\n valRet,messageInfo,traceBack=self.outputForConv2D(tempData)\n [j for j in tempData['properties'] if j['id']=='outputDimension' ][0]['value']=valRet\n elif tempData['layerType'] in ['DepthwiseConv2D']:\n valRet,messageInfo,traceBack=self.outputForDepthWiseConv2D(tempData)\n [j for j in tempData['properties'] if j['id']=='outputDimension' ][0]['value']=valRet\n elif tempData['layerType'] in ['Flatten']:\n valRet,messageInfo,traceBack=self.outputForFlatten(tempData)\n [j for j in tempData['properties'] if j['id']=='outputDimension' ][0]['value']=valRet\n elif tempData['layerType'] in ['ZeroPadding2D']:\n valRet,messageInfo,traceBack=self.outputFor2DPadding(tempData)\n [j for j in tempData['properties'] if j['id']=='outputDimension' ][0]['value']=valRet\n elif tempData['layerType'] in ['ZeroPadding1D']:\n valRet,messageInfo,traceBack=self.outputFor1DPadding(tempData)\n [j for j in tempData['properties'] if j['id']=='outputDimension' ][0]['value']=valRet\n elif tempData['layerType'] in ['Dense']:\n valRet,messageInfo,traceBack=self.outputForDense(tempData)\n [j for j in tempData['properties'] if j['id']=='outputDimension' ][0]['value']=valRet\n elif tempData['layerType'] in ['GlobalAveragePooling2D']:\n valRet,messageInfo,traceBack=self.outputForGlobalAverage2D(tempData)\n [j for j in tempData['properties'] if j['id']=='outputDimension' ][0]['value']=valRet\n elif tempData['layerType'] in ['MaxPooling2D', 'AveragePooling2D']:\n valRet,messageInfo,traceBack=self.outputForMaxPooling2D(tempData)\n [j for j in tempData['properties'] if j['id']=='outputDimension' ][0]['value']=valRet\n elif tempData['layerType'] in ['MaxPooling1D','AveragePooling1D']:\n valRet,messageInfo,traceBack=self.outputForMaxPooling1D(tempData)\n [j for j in tempData['properties'] if j['id']=='outputDimension' ][0]['value']=valRet\n # print ('NyokaUtilities $$$$$$$$$$$$$tempData',tempData)\n if messageInfo != 'success':\n tempData['errorMessage']=messageInfo\n tempData['errorTraceback']=traceBack\n return tempData\n\n\n ###################Below script is to get detaisl from a PMML file########################\n\n def getDataFields(self,tempObj):\n fieldNames=[]\n temp=tempObj['DataDictionary']\n temp=temp.get_DataField()\n for j in temp:\n fieldNames.append(j.name)\n return {'Column Names': fieldNames}\n\n\n def getHeaderInfo(self,tempObj):\n temp=tempObj['Header']\n tempDict={}\n tempDict['Time File Created']=temp.Timestamp.get_valueOf_()\n tempDict['Description']=temp.description\n return tempDict\n\n def getInfoNearestNeighborModel(self,tempObj):\n temp=tempObj['NearestNeighborModel'][0]\n tempDict={}\n tempDict['Model information']=[]\n tempDict['Model information'].append({'Algorithm Name':temp.algorithmName})\n tempDict['Model information'].append({'Function Type':temp.functionName})\n tempDict['Model information'].append({'Model Name':temp.modelName})\n tempDict['Model information'].append({'Number Of Neighbours':temp.numberOfNeighbors})\n return tempDict\n\n def getInfoOfDeepNetwork(self,tempObj):\n temp=tempObj['DeepNetwork'][0]\n tempDict={}\n tempDict['DeepNetwork information']=[]\n tempDict['DeepNetwork information'].append({'Function Type':temp.functionName})\n tempDict['DeepNetwork information'].append({'Model Name':temp.modelName})\n tempDict['DeepNetwork information'].append({'Number Of Layers':temp.numberOfLayers})\n return tempDict\n\n def getInfoMiningModel(self,tempObj):\n temp=tempObj['MiningModel'][0]\n tempDict={}\n tempDict['Model information']=[]\n tempDict['Model information'].append({'Function Type':temp.functionName})\n tempDict['Model information'].append({'Model Name':temp.modelName})\n if temp.Segmentation.multipleModelMethod=='modelChain':\n tempDict['Model information'].append({'Number of trees':len(temp.Segmentation.Segment[0].MiningModel.Segmentation.Segment)})\n else:\n tempDict['Model information'].append({'Number of trees':len(temp.Segmentation.Segment)})\n tempDict['Model information'].append({'Model Method':temp.Segmentation.multipleModelMethod})\n return tempDict\n\n\n\n def getInfoSupportVectorMachineModel(self,tempObj):\n temp=tempObj['SupportVectorMachineModel'][0]\n tempDict={}\n tempDict['Model information']=[]\n tempDict['Model information'].append({'Function Type':temp.functionName})\n tempDict['Model information'].append({'Model Name':temp.modelName})\n tempDict['Model information'].append({'Model Kernel description':temp.RadialBasisKernelType.description})\n tempDict['Model information'].append({'Model Method':temp.classificationMethod})\n return tempDict\n\n\n def getInfoTreeModel(self,tempObj):\n temp=tempObj['TreeModel'][0]\n tempDict={}\n tempDict['Model information']=[]\n tempDict['Model information'].append({'Function Type':temp.functionName})\n tempDict['Model information'].append({'Model Name':temp.modelName})\n return tempDict\n\n def getInfoLinearModel(self,tempObj):\n temp=tempObj['RegressionModel'][0]\n tempDict={}\n tempDict['Model information']=[]\n tempDict['Model information'].append({'Function Type':temp.functionName})\n tempDict['Model information'].append({'Model Name':temp.modelName})\n return tempDict\n\n\n def getInfoOfNaiveBayesModel(self,tempObj):\n temp=tempObj['NaiveBayesModel'][0]\n tempDict={}\n tempDict['Model information']=[]\n tempDict['Model information'].append({'Function Type':temp.functionName})\n tempDict['Model information'].append({'Model Name':temp.modelName})\n return tempDict\n \n def getInfoOfAnomalyDetectionModel(self,tempObj):\n temp=tempObj['AnomalyDetectionModel'][0]\n tempDict={}\n tempDict['Model information']=[]\n tempDict['Model information'].append({'Function Type':temp.functionName})\n tempDict['Model information'].append({'Model Name':temp.modelName})\n tempDict['Model information'].append({'Algorithm Type':temp.algorithmType})\n return tempDict\n \n\n def changeStructure(self,mm):\n allInfo={}\n allInfo['information']=[]\n for j in mm:\n if j in ['Model information','DeepNetwork information']:\n if j =='Model information':\n allInfo['modelGeneratedFrom']='SKLearn'\n else:\n allInfo['modelGeneratedFrom']='DeepNetwork'\n for k in mm[j]:\n for l in k:\n tempDict={}\n tempDict['property']=l\n tempDict['value']=k[l]\n allInfo['information'].append(tempDict)\n else:\n tempDict={}\n tempDict['property']=j\n tempDict['value']=mm[j]\n allInfo['information'].append(tempDict)\n\n if 'type' in mm:\n if mm['type']=='multi':\n allInfo['modelGeneratedFrom']='Workflow'\n\n\n return allInfo\n\n\n\n def pmmlToJson(self,filePath):\n pmmlObj=ny.parse(filePath,silence=True)\n pmmlDictObj=pmmlObj.__dict__\n\n # print ('0'*100,pmmlObj.get_type())\n\n if pmmlObj.get_type()=='multi':\n print ('came to Workflow')\n # print('*'*100)\n\n # print(PMMLMODELSTORAGE)\n # print('*'*100)\n \n import pathlib\n from trainModel.mergeTrainingV2 import TrainingViewModels\n pmmlFileObj=pathlib.Path(filePath)\n pmmlFileForKey=pmmlFileObj.name.replace(pmmlFileObj.suffix,'')\n from trainModel.mergeTrainingV2 import NewModelOperations\n NewModelOperations().loadExecutionModel(filePath)\n modelInformation=PMMLMODELSTORAGE[pmmlFileForKey]\n # print ('PMMLMODELSTORAGE after >>>>>>>>>>> ',PMMLMODELSTORAGE)\n # print (modelInformation)\n\n toexp=TrainingViewModels().restructureModelInforForExportDict(modelInformation)\n # print ('toexp'*20)\n # print ('toexportDictN >>>>>>>> ',toexp)\n \n import copy,json\n\n tempSec={\"name\":\"Section\", \"layerId\":\"Section\",\n \"children\":[], \"itemType\":\"FOLDING\", \"icon\":\"mdi mdi-group\", \"class\":\"wide\",\n \"modelType\":\"Workflow\", \"id\":\"id\", \"sectionId\":\"modName\", \"layerIndex\":None,'connectionLayerId':None}\n\n tempData={\"name\":\"Data\",\"icon\":\"mdi mdi-database-plus\",\"itemType\":\"DATA\",\"layerId\":None,\n \"trainable\":False,\"modelType\":\"Workflow\",\"id\":None,\"layerIndex\":None,\"connectionLayerId\":None,\n \"url\":None,\"filePath\":None}\n\n tempCode={\"name\":\"Code\",\"icon\":\"mdi mdi-code-braces\",\"itemType\":\"CODE\",\"layerId\":None,\n \"trainable\":False,\"modelType\":\"Workflow\",\"id\":\"K2PVI4HZ3NBGF\",\"layerIndex\":None,\"connectionLayerId\":None,\n \"url\":None,\"filePath\":None, \"taskType\":None,\"scriptOutput\":None,\"scriptPurpose\":None}\n\n tempModel={\"name\":\"Model\",\"icon\":\"mdi mdi-xml\",\"itemType\":\"MODEL\",\"layerId\":None,\"trainable\":False,\n \"modelType\":\"Workflow\",\"id\":None,\"layerIndex\":None,\"connectionLayerId\":None,\n \"url\":None,\"filePath\":None,\"taskType\":None}\n\n # toexp={'K2PSSUKYFRSMF': {'hyperparameters': None, \n # 'data': 'C:/Users/swsh/Desktop/ZMODGit/ZMOD/ZMOD/Data/newData2', \n # 'preProcessingScript': {'scripts': ['def addVal(x):\\n return x\\n'], 'scriptpurpose': ['trainAndscore'], 'scriptOutput': ['DATA'], 'scriptPath': ['C:/Users/swsh/Desktop/ZMODGit/ZMOD/ZMOD/Code/scriptToTest.py']}, \n # 'modelObj': None, \n # 'pipelineObj': None, \n # 'featuresUsed': ['cylinders', 'displacement', 'horsepower', 'weight', 'acceleration'], \n # 'targetName': 'mpg', \n # 'postProcessingScript': {'scripts': [], 'scriptpurpose': [], 'scriptOutput': [], 'scriptPath': []}, \n # 'taskType': 'trainAndscore', \n # 'modelPath': 'C:\\\\Users\\\\swsh\\\\Desktop\\\\ZMODGit\\\\ZMOD\\\\ZMOD\\\\Models\\\\autoML2.pmml'}}\n\n\n workflowArch=[]\n for modTemp in list(toexp.keys()):\n temSecCop=copy.deepcopy(tempSec)#.copy()\n temSecCop['sectionId']=modTemp\n temSecCop[\"layerId\"]=modTemp\n if toexp[modTemp]['data'] != None:\n dataInfo=copy.deepcopy(tempData)\n import pathlib\n fileName=pathlib.Path(toexp[modTemp]['data']).name\n dataInfo['layerId']=fileName\n dataInfo['url']='/Data/'+fileName\n dataInfo['filePath']=toexp[modTemp]['data']\n temSecCop['children'].append(dataInfo)\n for numSc,sC in enumerate(toexp[modTemp]['preProcessingScript']['scriptPath']):\n codeInfo=copy.deepcopy(tempCode)\n fileName=pathlib.Path(toexp[modTemp]['preProcessingScript']['scriptPath'][numSc]).name\n codeInfo['layerId']=fileName\n codeInfo['url']='/Code/'+fileName\n codeInfo['filePath']=toexp[modTemp]['preProcessingScript']['scriptPath'][numSc]\n codeInfo['taskType']='PREPROCESSING'\n codeInfo['scriptOutput']=toexp[modTemp]['preProcessingScript']['scriptOutput'][numSc]\n codeInfo['scriptPurpose']=toexp[modTemp]['preProcessingScript']['scriptpurpose'][numSc]\n temSecCop['children'].append(codeInfo)\n \n \n modtempC=copy.deepcopy(tempModel)\n fileName=pathlib.Path(toexp[modTemp]['modelPath']).name\n modtempC['layerId']=fileName\n modtempC['url']='/Model/'+fileName\n modtempC['filePath']=toexp[modTemp]['modelPath']\n modtempC['taskType']=toexp[modTemp]['taskType']\n temSecCop['children'].append(modtempC)\n \n \n for numSc,sC in enumerate(toexp[modTemp]['postProcessingScript']['scriptPath']):\n codeInfo=copy.deepcopy(tempCode)\n fileName=pathlib.Path(toexp[modTemp]['postProcessingScript']['scriptPath'][numSc]).name\n codeInfo['layerId']=fileName\n codeInfo['url']='/Code/'+fileName\n codeInfo['filePath']=toexp[modTemp]['postProcessingScript']['scriptPath'][numSc]\n codeInfo['taskType']='POSTPROCESSING'\n codeInfo['scriptOutput']=toexp[modTemp]['postProcessingScript']['scriptOutput'][numSc]\n codeInfo['scriptPurpose']=toexp[modTemp]['postProcessingScript']['scriptpurpose'][numSc]\n temSecCop['children'].append(codeInfo)\n \n workflowArch.append(temSecCop)\n \n from random import choice\n from string import ascii_uppercase\n\n for num,i in enumerate(workflowArch):\n if i['itemType']=='FOLDING':\n i['layerIndex']=num\n i['id']=''.join(choice(ascii_uppercase) for i in range(12))\n for num2,j in enumerate(i['children']):\n j['layerIndex']=num2\n j['id']=''.join(choice(ascii_uppercase) for i in range(12))\n else:\n i['layerIndex']=num\n i['id']=''.join(choice(ascii_uppercase) for i in range(12))\n # print ('l'*200)\n # print ('workflowArch',workflowArch)\n return workflowArch\n else:\n overAll=[]\n\n deepObject=pmmlDictObj['DeepNetwork'][0]\n listOfNetworkLayer=deepObject.NetworkLayer\n for lay in listOfNetworkLayer:\n networkDict=lay.__dict__\n tempDict={}\n tempDict['layerParam']={}\n tempDict['netParam']={}\n for j in networkDict:\n if networkDict[j] is not None:\n if j not in [ 'original_tagname_','LayerWeights','LayerParameters','Extension','LayerBias']:\n tempDict['netParam'][j]=networkDict[j]\n layerDict=networkDict['LayerParameters'].__dict__ \n for kk in layerDict:\n if layerDict[kk] is not None:\n if kk not in [ 'original_tagname_','Extension']:\n try:\n evalVal=list(ast.literal_eval(layerDict[kk]))\n except:\n evalVal=layerDict[kk]\n tempDict['layerParam'][kk]=evalVal\n tempDict['layerParam']['trainable']=False if layerDict['trainable'] == False else True\n\n if len(networkDict['Extension']) > 0:\n ttt=networkDict['Extension'][0]\n sectionVal=ttt.get_value()\n import ast\n tempDict['sectionId']=ast.literal_eval(sectionVal)['sectionId']\n else:\n tempDict['sectionId']=None\n overAll.append(tempDict)\n\n allLayers=MEMORY_OF_LAYERS['layerinfo'][0]['layers']\n listOFLayersName=[j['name'] for j in MEMORY_OF_LAYERS['layerinfo'][0]['layers']]\n architecture=[]\n for tempLay in overAll:\n import copy\n tempSpace=copy.deepcopy(allLayers[listOFLayersName.index(tempLay['netParam']['layerType'])])\n \n layerPARA=tempLay['layerParam']\n netWorkPARA=tempLay['netParam']\n for j in netWorkPARA:\n try:\n tempSpace[j]=netWorkPARA[j]\n except:\n pass\n\n for k in layerPARA:\n for k2 in tempSpace['properties']:\n if k2['id']==k:\n k2['value']=layerPARA[k]\n \n try:\n tempSpace['sectionId']=tempLay['sectionId']\n except:\n pass\n tempSpace['trainable']=layerPARA['trainable']\n architecture.append(tempSpace)\n \n forLoopSection=[j['sectionId'] for j in architecture]\n # print ('forLoopSection $$$$$$$$$$$$$$$',forLoopSection)\n tempSection={'children': [],'class': 'wide','icon': 'mdi mdi-group','id': '',\n 'itemType': 'FOLDING','layerId': 'Section','layerIndex': '','name': 'Section',\n 'sectionId': '',\"sectionCollapse\":True}\n\n import copy\n\n newarchitecture=[]\n tempSectionA=copy.deepcopy(tempSection)\n for num,secInfo in enumerate(forLoopSection):\n if secInfo is None:\n newarchitecture.append(architecture[num])\n else:\n if (num+1 < len(forLoopSection)) and (forLoopSection[num]==forLoopSection[num+1]):\n tempSectionA['children'].append(architecture[num])\n else:\n tempSectionA['children'].append(architecture[num])\n tempSectionA['sectionId']=secInfo\n tempSectionA['layerId']='Section_'+str(num)\n tempSectionA['name']='Section_'+str(num)\n newarchitecture.append(tempSectionA)\n tempSectionA=copy.deepcopy(tempSection)\n \n hd=pmmlDictObj['Header']\n scrptVal=pmmlDictObj['script']\n DataVal=pmmlDictObj['Data']\n import ast,pathlib\n try:\n try:\n dataUrl=DataVal[0].filePath\n except:\n dataUrl='Some issue'\n print ('$$$$$$$$$$$$$$$$$$$$$$',dataUrl)\n if dataUrl !='Some issue':\n fObj=pathlib.Path(dataUrl)\n dataCon={'icon': 'mdi mdi-database-plus','id': 'NNN',\n 'itemType': 'DATA','layerId':fObj.name ,'layerIndex': 0,'name': 'Data','url': dataUrl}\n newarchitecture.insert(0,dataCon)\n\n for counT,sc in enumerate(scrptVal):\n import pathlib\n scriptPurpose=sc.scriptPurpose\n modelVal=sc.for_\n classVal=sc.class_\n filePathUrl=sc.filePath\n fObjScrpt=pathlib.Path(filePathUrl)\n scriptCon= {\"name\": \"Code\",\"icon\": \"mdi mdi-code-braces\",\"itemType\": \"CODE\",\"modelFor\":modelVal,\n \"layerId\": fObjScrpt.name,\"scriptPurpose\":scriptPurpose,'url':filePathUrl,\"layerIndex\": \"NA\",'useFor':classVal}\n newarchitecture.insert(counT+1,scriptCon)\n else:\n pass\n\n except Exception as e:\n for counT,sc in enumerate(scrptVal):\n scriptUrl=sc.class_\n import pathlib\n fObjScrpt=pathlib.Path(scriptUrl)\n scriptCon= {\"name\": \"Code\",\"icon\": \"mdi mdi-code-braces\",\"itemType\": \"CODE\",\n \"layerId\": fObjScrpt.name,'url':scriptUrl,\"layerIndex\": \"NA\"}\n newarchitecture.insert(counT,scriptCon)\n print (e,'some error occured')\n\n for num,i in enumerate(newarchitecture):\n if i['itemType']=='FOLDING':\n i['layerIndex']=num\n i['id']=''.join(choice(ascii_uppercase) for i in range(12))\n for num2,j in enumerate(i['children']):\n j['layerIndex']=num2\n j['id']=''.join(choice(ascii_uppercase) for i in range(12))\n else:\n i['layerIndex']=num\n from random import choice\n from string import ascii_uppercase\n i['id']=''.join(choice(ascii_uppercase) for i in range(12))\n \n return newarchitecture\n\n\n #####################Add Update layer Utility Functions\n\n def checkItemType(self,inputDict):\n return inputDict['itemType']\n\n def checkChildren(self,inputDict):\n try:\n kk= inputDict['children']\n return True\n except:\n return False\n\n def getIndexOfInput(self,inputDict):\n return inputDict['layerIndex']\n\n def getIdOfInput(self,inputDict):\n return inputDict['id']\n\n def getIdOfSection(self,inputDict):\n try:\n return inputDict['sectionId']\n except:\n return None\n\n def addindex(self,inputDict):\n inputDict['layerIndex']=inputDict['layerIndex']+1\n return inputDict\n\n def getTemplateId(processTheInput):\n try:\n return processTheInput['templateId']\n except:\n return None\n\n def detailsofExistingArch(self,existingArch):\n listOFIndices=[i['layerIndex'] for i in existingArch]\n listOFIDS=[]\n listOfIdOFSections=[]\n listOfIdOFLayers=[]\n for j in existingArch:\n listOfIdOFLayers.append(j['id'])\n if j['itemType']=='FOLDING':\n for k in j['children']:\n # print ('###################Came')\n listOFIDS.append(k['id'])\n listOfIdOFSections.append(k['id'])\n else:\n listOFIDS.append(j['id'])\n return (listOFIDS,listOFIndices,listOfIdOFSections,listOfIdOFLayers)\n\n def getLayerType(self,processTheInput):\n # print ('processTheInput',processTheInput)\n try:\n if processTheInput['itemType'] =='FOLDING':\n return 'SECTION'\n elif processTheInput['itemType']=='TEMPLATE':\n return 'TEMPLATE'\n elif processTheInput['itemType'] == 'LAYER':\n try:\n kk=processTheInput['sectionId']\n if kk != None:\n return 'SECTION'\n else:\n return 'LAYER'\n except:\n return 'LAYER'\n else:\n return 'LAYER'\n except:\n if processTheInput['itemType']=='TEMPLATE':\n return 'TEMPLATE'\n else:\n return 'LAYER'\n \n \n def checkAboutChildren(self,processTheInput):\n try:\n val=processTheInput['children']\n return True\n except:\n return False\n \n def hasSectionID(self,processTheInput):\n try:\n processTheInput['sectionId']\n return True\n except:\n False\n\n def detailsofSectionArch(self,sectionArch):\n listOFIDS=[i['id'] for i in sectionArch['children']]\n listOFIndices=[i['layerIndex'] for i in sectionArch['children']]\n listOFIdIndex=[(i['layerIndex'],i['id']) for i in sectionArch['children']]\n return (listOFIDS,listOFIndices,listOFIdIndex)\n \n def makeModification(self,existingArch,processTheInput):\n indexInObj=self.getIndexOfInput(processTheInput)\n newArch=[]\n for lay in existingArch:\n _layIndex=self.getIndexOfInput(lay)\n if _layIndex==indexInObj:\n # print ('>>>>{} Index {} is equal to layer'.format(_layIndex,indexInObj))\n newArch.append(processTheInput.copy())\n lay1=self.addindex(lay)\n newArch.append(lay1.copy())\n elif _layIndex < indexInObj:\n # print ('>>>>{} Index {} is greater to layer'.format(_layIndex,indexInObj))\n newArch.append(lay.copy())\n # newArch.append(processTheInput.copy())\n elif _layIndex > indexInObj:\n # print ('>>>>{} Index {} is lesser to layer'.format(_layIndex,indexInObj))\n lay1=self.addindex(lay)\n newArch.append(lay1.copy())\n \n return newArch"
] | [
[
"numpy.prod"
]
] |
h8907283/dm_control | [
"4e1a35595124742015ae0c7a829e099a5aa100f5"
] | [
"dm_control/suite/quadruped.py"
] | [
"# Copyright 2019 The dm_control Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\n\"\"\"Quadruped Domain.\"\"\"\n\nimport collections\n\nfrom dm_control import mujoco\nfrom dm_control.mujoco.wrapper import mjbindings\nfrom dm_control.rl import control\nfrom dm_control.suite import base\nfrom dm_control.suite import common\nfrom dm_control.utils import containers\nfrom dm_control.utils import rewards\nfrom dm_control.utils import xml_tools\nfrom lxml import etree\nimport numpy as np\nfrom scipy import ndimage\n\nenums = mjbindings.enums\nmjlib = mjbindings.mjlib\n\n\n_DEFAULT_TIME_LIMIT = 20\n_CONTROL_TIMESTEP = .02\n\n# Horizontal speeds above which the move reward is 1.\n_RUN_SPEED = 5\n_WALK_SPEED = 0.5\n\n# Constants related to terrain generation.\n_HEIGHTFIELD_ID = 0\n_TERRAIN_SMOOTHNESS = 0.15 # 0.0: maximally bumpy; 1.0: completely smooth.\n_TERRAIN_BUMP_SCALE = 2 # Spatial scale of terrain bumps (in meters).\n\n# Named model elements.\n_TOES = ['toe_front_left', 'toe_back_left', 'toe_back_right', 'toe_front_right']\n_WALLS = ['wall_px', 'wall_py', 'wall_nx', 'wall_ny']\n\nSUITE = containers.TaggedTasks()\n\n\ndef make_model(floor_size=None, terrain=False, rangefinders=False,\n walls_and_ball=False):\n \"\"\"Returns the model XML string.\"\"\"\n xml_string = common.read_model('quadruped.xml')\n parser = etree.XMLParser(remove_blank_text=True)\n mjcf = etree.XML(xml_string, parser)\n\n # Set floor size.\n if floor_size is not None:\n floor_geom = mjcf.find('.//geom[@name=\\'floor\\']')\n floor_geom.attrib['size'] = f'{floor_size} {floor_size} .5'\n\n # Remove walls, ball and target.\n if not walls_and_ball:\n for wall in _WALLS:\n wall_geom = xml_tools.find_element(mjcf, 'geom', wall)\n wall_geom.getparent().remove(wall_geom)\n\n # Remove ball.\n ball_body = xml_tools.find_element(mjcf, 'body', 'ball')\n ball_body.getparent().remove(ball_body)\n\n # Remove target.\n target_site = xml_tools.find_element(mjcf, 'site', 'target')\n target_site.getparent().remove(target_site)\n\n # Remove terrain.\n if not terrain:\n terrain_geom = xml_tools.find_element(mjcf, 'geom', 'terrain')\n terrain_geom.getparent().remove(terrain_geom)\n\n # Remove rangefinders if they're not used, as range computations can be\n # expensive, especially in a scene with heightfields.\n if not rangefinders:\n rangefinder_sensors = mjcf.findall('.//rangefinder')\n for rf in rangefinder_sensors:\n rf.getparent().remove(rf)\n\n return etree.tostring(mjcf, pretty_print=True)\n\n\[email protected]()\ndef walk(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):\n \"\"\"Returns the Walk task.\"\"\"\n xml_string = make_model(floor_size=_DEFAULT_TIME_LIMIT * _WALK_SPEED)\n physics = Physics.from_xml_string(xml_string, common.ASSETS)\n task = Move(desired_speed=_WALK_SPEED, random=random)\n environment_kwargs = environment_kwargs or {}\n return control.Environment(physics, task, time_limit=time_limit,\n control_timestep=_CONTROL_TIMESTEP,\n **environment_kwargs)\n\n\[email protected]()\ndef run(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):\n \"\"\"Returns the Run task.\"\"\"\n xml_string = make_model(floor_size=_DEFAULT_TIME_LIMIT * _RUN_SPEED)\n physics = Physics.from_xml_string(xml_string, common.ASSETS)\n task = Move(desired_speed=_RUN_SPEED, random=random)\n environment_kwargs = environment_kwargs or {}\n return control.Environment(physics, task, time_limit=time_limit,\n control_timestep=_CONTROL_TIMESTEP,\n **environment_kwargs)\n\n\[email protected]()\ndef escape(time_limit=_DEFAULT_TIME_LIMIT, random=None,\n environment_kwargs=None):\n \"\"\"Returns the Escape task.\"\"\"\n xml_string = make_model(floor_size=40, terrain=True, rangefinders=True)\n physics = Physics.from_xml_string(xml_string, common.ASSETS)\n task = Escape(random=random)\n environment_kwargs = environment_kwargs or {}\n return control.Environment(physics, task, time_limit=time_limit,\n control_timestep=_CONTROL_TIMESTEP,\n **environment_kwargs)\n\n\[email protected]()\ndef fetch(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):\n \"\"\"Returns the Fetch task.\"\"\"\n xml_string = make_model(walls_and_ball=True)\n physics = Physics.from_xml_string(xml_string, common.ASSETS)\n task = Fetch(random=random)\n environment_kwargs = environment_kwargs or {}\n return control.Environment(physics, task, time_limit=time_limit,\n control_timestep=_CONTROL_TIMESTEP,\n **environment_kwargs)\n\n\nclass Physics(mujoco.Physics):\n \"\"\"Physics simulation with additional features for the Quadruped domain.\"\"\"\n\n def _reload_from_data(self, data):\n super()._reload_from_data(data)\n # Clear cached sensor names when the physics is reloaded.\n self._sensor_types_to_names = {}\n self._hinge_names = []\n\n def _get_sensor_names(self, *sensor_types):\n try:\n sensor_names = self._sensor_types_to_names[sensor_types]\n except KeyError:\n [sensor_ids] = np.where(np.in1d(self.model.sensor_type, sensor_types))\n sensor_names = [self.model.id2name(s_id, 'sensor') for s_id in sensor_ids]\n self._sensor_types_to_names[sensor_types] = sensor_names\n return sensor_names\n\n def torso_upright(self):\n \"\"\"Returns the dot-product of the torso z-axis and the global z-axis.\"\"\"\n return np.asarray(self.named.data.xmat['torso', 'zz'])\n\n def torso_velocity(self):\n \"\"\"Returns the velocity of the torso, in the local frame.\"\"\"\n return self.named.data.sensordata['velocimeter'].copy()\n\n def egocentric_state(self):\n \"\"\"Returns the state without global orientation or position.\"\"\"\n if not self._hinge_names:\n [hinge_ids] = np.nonzero(self.model.jnt_type ==\n enums.mjtJoint.mjJNT_HINGE)\n self._hinge_names = [self.model.id2name(j_id, 'joint')\n for j_id in hinge_ids]\n return np.hstack((self.named.data.qpos[self._hinge_names],\n self.named.data.qvel[self._hinge_names],\n self.data.act))\n\n def toe_positions(self):\n \"\"\"Returns toe positions in egocentric frame.\"\"\"\n torso_frame = self.named.data.xmat['torso'].reshape(3, 3)\n torso_pos = self.named.data.xpos['torso']\n torso_to_toe = self.named.data.xpos[_TOES] - torso_pos\n return torso_to_toe.dot(torso_frame)\n\n def force_torque(self):\n \"\"\"Returns scaled force/torque sensor readings at the toes.\"\"\"\n force_torque_sensors = self._get_sensor_names(enums.mjtSensor.mjSENS_FORCE,\n enums.mjtSensor.mjSENS_TORQUE)\n return np.arcsinh(self.named.data.sensordata[force_torque_sensors])\n\n def imu(self):\n \"\"\"Returns IMU-like sensor readings.\"\"\"\n imu_sensors = self._get_sensor_names(enums.mjtSensor.mjSENS_GYRO,\n enums.mjtSensor.mjSENS_ACCELEROMETER)\n return self.named.data.sensordata[imu_sensors]\n\n def rangefinder(self):\n \"\"\"Returns scaled rangefinder sensor readings.\"\"\"\n rf_sensors = self._get_sensor_names(enums.mjtSensor.mjSENS_RANGEFINDER)\n rf_readings = self.named.data.sensordata[rf_sensors]\n no_intersection = -1.0\n return np.where(rf_readings == no_intersection, 1.0, np.tanh(rf_readings))\n\n def origin_distance(self):\n \"\"\"Returns the distance from the origin to the workspace.\"\"\"\n return np.asarray(np.linalg.norm(self.named.data.site_xpos['workspace']))\n\n def origin(self):\n \"\"\"Returns origin position in the torso frame.\"\"\"\n torso_frame = self.named.data.xmat['torso'].reshape(3, 3)\n torso_pos = self.named.data.xpos['torso']\n return -torso_pos.dot(torso_frame)\n\n def ball_state(self):\n \"\"\"Returns ball position and velocity relative to the torso frame.\"\"\"\n data = self.named.data\n torso_frame = data.xmat['torso'].reshape(3, 3)\n ball_rel_pos = data.xpos['ball'] - data.xpos['torso']\n ball_rel_vel = data.qvel['ball_root'][:3] - data.qvel['root'][:3]\n ball_rot_vel = data.qvel['ball_root'][3:]\n ball_state = np.vstack((ball_rel_pos, ball_rel_vel, ball_rot_vel))\n return ball_state.dot(torso_frame).ravel()\n\n def target_position(self):\n \"\"\"Returns target position in torso frame.\"\"\"\n torso_frame = self.named.data.xmat['torso'].reshape(3, 3)\n torso_pos = self.named.data.xpos['torso']\n torso_to_target = self.named.data.site_xpos['target'] - torso_pos\n return torso_to_target.dot(torso_frame)\n\n def ball_to_target_distance(self):\n \"\"\"Returns horizontal distance from the ball to the target.\"\"\"\n ball_to_target = (self.named.data.site_xpos['target'] -\n self.named.data.xpos['ball'])\n return np.linalg.norm(ball_to_target[:2])\n\n def self_to_ball_distance(self):\n \"\"\"Returns horizontal distance from the quadruped workspace to the ball.\"\"\"\n self_to_ball = (self.named.data.site_xpos['workspace']\n -self.named.data.xpos['ball'])\n return np.linalg.norm(self_to_ball[:2])\n\n\ndef _find_non_contacting_height(physics, orientation, x_pos=0.0, y_pos=0.0):\n \"\"\"Find a height with no contacts given a body orientation.\n\n Args:\n physics: An instance of `Physics`.\n orientation: A quaternion.\n x_pos: A float. Position along global x-axis.\n y_pos: A float. Position along global y-axis.\n Raises:\n RuntimeError: If a non-contacting configuration has not been found after\n 10,000 attempts.\n \"\"\"\n z_pos = 0.0 # Start embedded in the floor.\n num_contacts = 1\n num_attempts = 0\n # Move up in 1cm increments until no contacts.\n while num_contacts > 0:\n try:\n with physics.reset_context():\n physics.named.data.qpos['root'][:3] = x_pos, y_pos, z_pos\n physics.named.data.qpos['root'][3:] = orientation\n except control.PhysicsError:\n # We may encounter a PhysicsError here due to filling the contact\n # buffer, in which case we simply increment the height and continue.\n pass\n num_contacts = physics.data.ncon\n z_pos += 0.01\n num_attempts += 1\n if num_attempts > 10000:\n raise RuntimeError('Failed to find a non-contacting configuration.')\n\n\ndef _common_observations(physics):\n \"\"\"Returns the observations common to all tasks.\"\"\"\n obs = collections.OrderedDict()\n obs['egocentric_state'] = physics.egocentric_state()\n obs['torso_velocity'] = physics.torso_velocity()\n obs['torso_upright'] = physics.torso_upright()\n obs['imu'] = physics.imu()\n obs['force_torque'] = physics.force_torque()\n return obs\n\n\ndef _upright_reward(physics, deviation_angle=0):\n \"\"\"Returns a reward proportional to how upright the torso is.\n\n Args:\n physics: an instance of `Physics`.\n deviation_angle: A float, in degrees. The reward is 0 when the torso is\n exactly upside-down and 1 when the torso's z-axis is less than\n `deviation_angle` away from the global z-axis.\n \"\"\"\n deviation = np.cos(np.deg2rad(deviation_angle))\n return rewards.tolerance(\n physics.torso_upright(),\n bounds=(deviation, float('inf')),\n sigmoid='linear',\n margin=1 + deviation,\n value_at_margin=0)\n\n\nclass Move(base.Task):\n \"\"\"A quadruped task solved by moving forward at a designated speed.\"\"\"\n\n def __init__(self, desired_speed, random=None):\n \"\"\"Initializes an instance of `Move`.\n\n Args:\n desired_speed: A float. If this value is zero, reward is given simply\n for standing upright. Otherwise this specifies the horizontal velocity\n at which the velocity-dependent reward component is maximized.\n random: Optional, either a `numpy.random.RandomState` instance, an\n integer seed for creating a new `RandomState`, or None to select a seed\n automatically (default).\n \"\"\"\n self._desired_speed = desired_speed\n super().__init__(random=random)\n\n def initialize_episode(self, physics):\n \"\"\"Sets the state of the environment at the start of each episode.\n\n Args:\n physics: An instance of `Physics`.\n\n \"\"\"\n # Initial configuration.\n orientation = self.random.randn(4)\n orientation /= np.linalg.norm(orientation)\n _find_non_contacting_height(physics, orientation)\n super().initialize_episode(physics)\n\n def get_observation(self, physics):\n \"\"\"Returns an observation to the agent.\"\"\"\n return _common_observations(physics)\n\n def get_reward(self, physics):\n \"\"\"Returns a reward to the agent.\"\"\"\n\n # Move reward term.\n move_reward = rewards.tolerance(\n physics.torso_velocity()[0],\n bounds=(self._desired_speed, float('inf')),\n margin=self._desired_speed,\n value_at_margin=0.5,\n sigmoid='linear')\n\n return _upright_reward(physics) * move_reward\n\n\nclass Escape(base.Task):\n \"\"\"A quadruped task solved by escaping a bowl-shaped terrain.\"\"\"\n\n def initialize_episode(self, physics):\n \"\"\"Sets the state of the environment at the start of each episode.\n\n Args:\n physics: An instance of `Physics`.\n\n \"\"\"\n # Get heightfield resolution, assert that it is square.\n res = physics.model.hfield_nrow[_HEIGHTFIELD_ID]\n assert res == physics.model.hfield_ncol[_HEIGHTFIELD_ID]\n # Sinusoidal bowl shape.\n row_grid, col_grid = np.ogrid[-1:1:res*1j, -1:1:res*1j]\n radius = np.clip(np.sqrt(col_grid**2 + row_grid**2), .04, 1)\n bowl_shape = .5 - np.cos(2*np.pi*radius)/2\n # Random smooth bumps.\n terrain_size = 2 * physics.model.hfield_size[_HEIGHTFIELD_ID, 0]\n bump_res = int(terrain_size / _TERRAIN_BUMP_SCALE)\n bumps = self.random.uniform(_TERRAIN_SMOOTHNESS, 1, (bump_res, bump_res))\n smooth_bumps = ndimage.zoom(bumps, res / float(bump_res))\n # Terrain is elementwise product.\n terrain = bowl_shape * smooth_bumps\n start_idx = physics.model.hfield_adr[_HEIGHTFIELD_ID]\n physics.model.hfield_data[start_idx:start_idx+res**2] = terrain.ravel()\n super().initialize_episode(physics)\n\n # If we have a rendering context, we need to re-upload the modified\n # heightfield data.\n if physics.contexts:\n with physics.contexts.gl.make_current() as ctx:\n ctx.call(mjlib.mjr_uploadHField,\n physics.model.ptr,\n physics.contexts.mujoco.ptr,\n _HEIGHTFIELD_ID)\n\n # Initial configuration.\n orientation = self.random.randn(4)\n orientation /= np.linalg.norm(orientation)\n _find_non_contacting_height(physics, orientation)\n\n def get_observation(self, physics):\n \"\"\"Returns an observation to the agent.\"\"\"\n obs = _common_observations(physics)\n obs['origin'] = physics.origin()\n obs['rangefinder'] = physics.rangefinder()\n return obs\n\n def get_reward(self, physics):\n \"\"\"Returns a reward to the agent.\"\"\"\n\n # Escape reward term.\n terrain_size = physics.model.hfield_size[_HEIGHTFIELD_ID, 0]\n escape_reward = rewards.tolerance(\n physics.origin_distance(),\n bounds=(terrain_size, float('inf')),\n margin=terrain_size,\n value_at_margin=0,\n sigmoid='linear')\n\n return _upright_reward(physics, deviation_angle=20) * escape_reward\n\n\nclass Fetch(base.Task):\n \"\"\"A quadruped task solved by bringing a ball to the origin.\"\"\"\n\n def initialize_episode(self, physics):\n \"\"\"Sets the state of the environment at the start of each episode.\n\n Args:\n physics: An instance of `Physics`.\n\n \"\"\"\n # Initial configuration, random azimuth and horizontal position.\n azimuth = self.random.uniform(0, 2*np.pi)\n orientation = np.array((np.cos(azimuth/2), 0, 0, np.sin(azimuth/2)))\n spawn_radius = 0.9 * physics.named.model.geom_size['floor', 0]\n x_pos, y_pos = self.random.uniform(-spawn_radius, spawn_radius, size=(2,))\n _find_non_contacting_height(physics, orientation, x_pos, y_pos)\n\n # Initial ball state.\n physics.named.data.qpos['ball_root'][:2] = self.random.uniform(\n -spawn_radius, spawn_radius, size=(2,))\n physics.named.data.qpos['ball_root'][2] = 2\n physics.named.data.qvel['ball_root'][:2] = 5*self.random.randn(2)\n super().initialize_episode(physics)\n\n def get_observation(self, physics):\n \"\"\"Returns an observation to the agent.\"\"\"\n obs = _common_observations(physics)\n obs['ball_state'] = physics.ball_state()\n obs['target_position'] = physics.target_position()\n return obs\n\n def get_reward(self, physics):\n \"\"\"Returns a reward to the agent.\"\"\"\n\n # Reward for moving close to the ball.\n arena_radius = physics.named.model.geom_size['floor', 0] * np.sqrt(2)\n workspace_radius = physics.named.model.site_size['workspace', 0]\n ball_radius = physics.named.model.geom_size['ball', 0]\n reach_reward = rewards.tolerance(\n physics.self_to_ball_distance(),\n bounds=(0, workspace_radius+ball_radius),\n sigmoid='linear',\n margin=arena_radius, value_at_margin=0)\n\n # Reward for bringing the ball to the target.\n target_radius = physics.named.model.site_size['target', 0]\n fetch_reward = rewards.tolerance(\n physics.ball_to_target_distance(),\n bounds=(0, target_radius),\n sigmoid='linear',\n margin=arena_radius, value_at_margin=0)\n\n reach_then_fetch = reach_reward * (0.5 + 0.5*fetch_reward)\n\n return _upright_reward(physics) * reach_then_fetch\n"
] | [
[
"numpy.vstack",
"numpy.arcsinh",
"numpy.in1d",
"numpy.asarray",
"numpy.cos",
"numpy.hstack",
"numpy.nonzero",
"numpy.sqrt",
"numpy.sin",
"numpy.linalg.norm",
"numpy.tanh",
"numpy.deg2rad"
]
] |
ProSeCo-Planning/ros_proseco_planning | [
"484beedb01e5faafa7e03e95bc88b1e4f969285e"
] | [
"python/proseco/evaluator/head.py"
] | [
"import os\nimport copy\nimport ray\nimport argparse\nimport tqdm\nimport logging\nimport pandas as pd\nfrom pathlib import Path\nfrom datetime import datetime\nimport shutil\nimport uuid as uu_id\nfrom typing import ClassVar, Dict, Generator, Tuple, List, Any\n\nfrom proseco.evaluator.remote import run\nfrom proseco.evaluator.progressBar import ProgressBar\nimport proseco.utility.io as io\nimport proseco.utility.ui as ui\nfrom proseco.dashboard.model import (\n get_run_directories,\n is_successful_result,\n load_result,\n load_options,\n load_scenario,\n load_uuid,\n)\nfrom proseco.evaluator.util import (\n flatten_dictionary,\n nest_dictionary,\n hash_dict,\n get_permutations,\n)\n\n\nclass Head:\n \"\"\"Head node of the Evaluation.\"\"\"\n\n pack_path: str\n args: argparse.Namespace\n bulk_config: Dict[str, Any]\n time_string: str\n number_evaluations: int\n iteration_index: int\n logger: logging.Logger\n c_error: ClassVar[str] = \"\\033[91m\\033[1m\"\n c_warning: ClassVar[str] = \"\\33[33m\\033[\"\n c_okay: ClassVar[str] = \"\\033[92m\\033[1m\"\n c_reset: ClassVar[str] = \"\\033[0m\"\n\n def __init__(\n self, args: argparse.Namespace, time_string: str = None, init_ray: bool = True\n ):\n \"\"\"Constructor.\n\n Parameters\n ----------\n args : argparse.Namespace\n Command line arguments for starting the evaluation.\n time_string : str\n Optional time stamp when this head node was started.\n init_ray : bool\n When True the evaluation will connect the local ray client to a cluster (default: True).\n It is used to prevent multiple ray-inits when running evaluations in sequence, else ray init will throw an exception.\n \"\"\"\n self.logger = ui.get_logger(\"ProSeCo Evaluator\")\n # Arguments with flags\n self.args = args\n # Openend config directory\n self.bulk_config = self.get_file(file_type=\"evaluator\", file=args.config)\n # Timestamp of the head node\n if time_string == None:\n self.time_string = io.create_timestamp()\n else:\n self.time_string = time_string\n # How many evaluations this config will generate\n self.number_evaluations = self.determine_number_evaluations()\n # The current iteration index the evaluation is at\n self.iteration_index = 0\n self.path = self.create_evaluation_directory()\n # The time in seconds, when a task is considered to be timed out.\n self.task_timeout = 120\n\n self.isolate_binary()\n self.init_ray()\n\n def __del__(self):\n \"\"\"Destructor.\n\n Removes the temporary binary for the evaluation.\n \"\"\"\n self.remove_binary()\n\n def determine_number_evaluations(self) -> int:\n \"\"\"Determines the number of MCTS-Evaluations to be started.\n\n Returns\n -------\n int\n Total number of scenario evaluations.\n \"\"\"\n len_options = len(self.bulk_config[\"options\"])\n len_scenarios = len(self.bulk_config[\"scenarios\"])\n number_runs = self.bulk_config[\"number_runs\"]\n\n alterations = flatten_dictionary(self.bulk_config[\"options_alterations\"])\n scenario_alterations = flatten_dictionary(\n self.bulk_config[\"scenario_alterations\"]\n )\n alterations.update(scenario_alterations)\n\n len_alter = 1\n for _, v in alterations.items():\n if type(v) is list:\n len_alter = len_alter * len(v)\n else:\n pass\n\n number_evaluations = len_options * len_scenarios * len_alter * number_runs\n\n return number_evaluations\n\n def create_evaluation_directory(self) -> Path:\n \"\"\"Creates a directory for the evaluation.\n\n Returns\n -------\n Path\n The path to the evaluation directory.\n \"\"\"\n path = (\n io.get_user_temp_dir()\n / f\"proseco_evaluator_output/{self.time_string}_{self.bulk_config['evaluation_name']}\"\n )\n path.mkdir(parents=True)\n self.logger.info(f\"Creating evaluation directory {path}\")\n return path\n\n def isolate_binary(self) -> None:\n \"\"\"Moves the binary to a unique directory, so that rebuilding the binary does not affect the evaluation.\"\"\"\n\n devel_binary_path = (Path(io.get_ros_pack_path()).parents[1]).joinpath(\n \"devel_isolated/ros_proseco_planning/lib/ros_proseco_planning\"\n )\n temp_binary_path = Path(f\"~/evaluator_bin_{self.time_string}\").expanduser()\n shutil.copytree(devel_binary_path, temp_binary_path)\n self.logger.debug(f\"Created temporary binary path {temp_binary_path}\")\n self.binary_path = temp_binary_path\n\n def remove_binary(self) -> None:\n \"\"\"Removes the temporary binary for the evaluation.\"\"\"\n self.logger.debug(f\"Removed temporary binary path {self.binary_path}\")\n shutil.rmtree(self.binary_path)\n\n def init_ray(self) -> None:\n \"\"\"Initializes the ray cluster, determines the maximum number of workers and creates the workers.\"\"\"\n self.logger.debug(f\"Initializing ray cluster\")\n ray.init(\n address=self.args.address or self.bulk_config[\"ray_cluster\"][\"address\"],\n include_dashboard=not self.args.no_dashboard,\n dashboard_host=\"0.0.0.0\",\n log_to_driver=self.args.debug,\n _temp_dir=str(io.get_user_temp_dir() / \"ray\"),\n )\n\n def print_evaluation_scenarios(self) -> None:\n \"\"\"Prints the different combinations of settings for the evaluation.\"\"\"\n self.logger.debug(f\"EVALUATOR CONFIGURATION: {self.bulk_config}\")\n scenarios = \",\".join(self.bulk_config[\"scenarios\"])\n self.logger.info(f\"Evaluating Scenarios: [{scenarios}]\")\n\n @staticmethod\n def permute_dictionary(\n dictionary: Dict[str, any], permutation: Dict[str, any]\n ) -> Dict[str, any]:\n \"\"\"Creates a new dictionary with the given permutation applied.\n\n Parameters\n ----------\n dictionary : Dict[str, any]\n The dictionary to apply the permutation to.\n permutation : Dict[str, any]\n The permutation to apply.\n\n Returns\n -------\n Dict[str, any]\n The new options dictionary.\n \"\"\"\n dictionary = flatten_dictionary(dictionary)\n dictionary.update(permutation)\n return nest_dictionary(dictionary)\n\n @staticmethod\n def remove_random_seed(options: Dict[str, any]) -> Dict[str, any]:\n \"\"\"Removes the random seed from the options.\n\n Parameters\n ----------\n options : Dict[str, any]\n The options to remove the random seed from.\n\n Returns\n -------\n Dict[str, any]\n The options without the random seed.\n \"\"\"\n options = copy.deepcopy(options)\n options[\"compute_options\"].pop(\"random_seed\")\n return options\n\n @staticmethod\n def hash_options_and_scenario(\n options: Dict[str, Any], scenario: Dict[str, Any]\n ) -> str:\n \"\"\"Hashes the options and the scenario.\n\n Parameters\n ----------\n options : Dict[str, Any]\n The options to hash.\n scenario : Dict[str, Any]\n The scenario to hash.\n\n Returns\n -------\n str\n The combination of the options and the scenario.\n \"\"\"\n options_scenario = {}\n options_scenario.update(options)\n options_scenario.update(scenario)\n return hash_dict(options_scenario)\n\n def get_file(self, file_type: str, file: str) -> Dict[str, Any]:\n \"\"\"Returns a scenario, config or options dictionary.\n\n The files are loaded via json.\n\n Parameters\n ----------\n file_type : str\n String indicating whether the file to load contains options, a scenario or a config for the evaluator.\n file : str\n Name of the file to load.\n\n Returns\n -------\n Dict[str, Any]\n Loaded options dictionary.\n \"\"\"\n if isinstance(file, dict):\n data = file\n\n elif type(file) is str:\n\n if not file.endswith(\".json\"):\n file += \".json\"\n\n if (\n file_type == \"options\"\n or file_type == \"scenarios\"\n or file_type == \"evaluator\"\n ):\n path = io.get_ros_pack_path() / \"config\" / file_type / file\n else:\n raise Exception(f\"Unknown file type {file_type}\")\n\n data = io.load_data(path)\n\n return data\n\n def options_iterator(\n self,\n ) -> Generator[\n Tuple[Dict[str, Dict[str, Any]], Dict[str, Any], List[str], Dict[str, Any]],\n None,\n None,\n ]:\n \"\"\"Defines an iterator for the option permutations.\n\n The iterator returns the necessary files for evaluating a scenario with a worker node.\n Additionally, it also returns an info dict used to update the progress bar.\n\n Yields\n -------\n options: Tuple[Dict[str, Dict[str, Any]], Dict[str, Any], List[str], Dict[str, Any]]\n Tuple containing all the necessary files to initiate an evaluation run. Contains:\n - new_options : Dictionary containing compute options.\n - new_scenario : Loaded scenario configuration.\n - uuid : Unique IDs and scenario-options hashes.\n - info_dict: Information to update the progress bar.\n \"\"\"\n\n # Iterate over all provided compute option files\n for options in self.bulk_config[\"options\"]:\n options = io.load_options(options)\n\n flat_options = flatten_dictionary(self.bulk_config[\"options_alterations\"])\n options_permutations = get_permutations(flat_options)\n\n # Iterate over all permutations of options alterations\n for options_permutation in options_permutations:\n self.logger.debug(f\"Permuting options with: {options_permutation}\")\n new_options = self.permute_dictionary(options, options_permutation)\n\n # Unique ID for the options file\n uuid_options = str(uu_id.uuid4())\n new_options_wo_random_seed = self.remove_random_seed(new_options)\n options_hash = hash_dict(new_options_wo_random_seed)\n\n # Iterate over every scenario\n for scenario in self.bulk_config[\"scenarios\"]:\n scenario = io.load_scenario(scenario)\n\n flat_scenario = flatten_dictionary(\n self.bulk_config[\"scenario_alterations\"]\n )\n scenarios_permutations = get_permutations(flat_scenario)\n\n # Iterate over all scenario permutations of the scenario alterations\n for scenarios_permutation in scenarios_permutations:\n self.logger.debug(\n f\"Permuting scenario with: {scenarios_permutation}\"\n )\n new_scenario = self.permute_dictionary(\n scenario, scenarios_permutation\n )\n\n # Unique ID for the options and scenario tuple\n uuid_scenario = str(uu_id.uuid4())\n options_scenario_hash = self.hash_options_and_scenario(\n new_options_wo_random_seed, new_scenario\n )\n\n uuids = {\n \"options_uuid\": uuid_options,\n \"options_scenario_uuid\": uuid_scenario,\n \"options_hash\": options_hash,\n \"options_scenario_hash\": options_scenario_hash,\n }\n\n # Iterate over number of runs\n for _ in range(self.bulk_config[\"number_runs\"]):\n yield new_options, new_scenario, uuids\n\n def run_tasks(self):\n \"\"\"Starts the tasks and waits for them to finish.\n\n Parameters\n ----------\n results : List[List[Any]]\n The list of results.\n \"\"\"\n pb = ProgressBar(self.number_evaluations)\n\n results_ref = []\n for options, scenario, uuids in self.options_iterator():\n results_ref.append(\n run.remote(\n options,\n scenario,\n uuids,\n self.binary_path,\n self.args.debug,\n pb.actor,\n )\n )\n pb.print_until_done_or_timeout(self.task_timeout)\n results = ray.get(results_ref)\n return results\n\n def start(self) -> Tuple[List[List[Any]], bool]:\n \"\"\"Creates all the ray futures according to the configuration file and evaluates them.\n\n Main method for running the evaluation and delegating tasks to workers.\n\n Notes\n -----\n If the result list becomes larger than 5GB, the result list returned by this method does not contain all results.\n The return value `complete` indicates whether all results are contained.\n Despite the limitation of the returned list, all results are always persisted to disk in the evaluation directory.\n\n Returns\n -------\n Tuple[List[List[Any]], bool]\n Tuple containing the results of the evaluation.\n The first element is a list with the current results.\n The second element is a boolean flag indicating whether the list contains ALL results.\n \"\"\"\n self.print_evaluation_scenarios()\n # Starting time of the evaluation\n beginning = datetime.now()\n\n results = self.run_tasks()\n self.save_results(results)\n\n # create summary json if specified\n if not self.args.no_summary:\n _ = self.create_summary(True)\n\n self.logger.info(\n f\"{self.c_okay}The {self.iteration_index}-th evaluation terminated successfully in {datetime.now()-beginning}{self.c_reset}\"\n )\n self.iteration_index += 1\n\n return results\n\n def save_results(self, results: List[List[Any]]) -> None:\n \"\"\"Saves the results to disk.\n\n Parameters\n ----------\n results : List[List[Any]]\n The list containing the results of all runs.\n \"\"\"\n\n for result_index in range(len(results)):\n self.save_result(results[result_index], result_index)\n\n def save_result(self, result: List[Any], result_index: int) -> None:\n \"\"\"Saves a single result to disk.\n\n Parameters\n ----------\n result : List[Any]\n The list containing the partial results of a single run.\n result_index : int\n The index of the result.\n \"\"\"\n result_path = (\n self.path\n / f\"iteration_{self.iteration_index}\"\n / f\"result_{str(result_index).zfill(io.get_number_digits(self.number_evaluations-1))}of{str(self.number_evaluations-1).zfill(io.get_number_digits(self.number_evaluations-1))}\"\n )\n result_path.mkdir(parents=True)\n\n for file_name, data in result:\n io.save_data(data, result_path / file_name)\n\n # append the path to the result\n result.append([\"%PATH%\", str(result_path)])\n\n @staticmethod\n def _check_alterations_key(key: str, value: Any) -> bool:\n \"\"\"Checks whether the specified key is being iterated over in the evaluator bulk config.\n\n Parameters\n ----------\n key : str\n String dictionary key of an options file.\n value : Any\n Dictionary value.\n\n Returns\n -------\n bool\n True if the key is a compute_options alteration, False else.\n \"\"\"\n return (\n isinstance(value, list)\n and key.startswith(\"options_alterations\")\n and not key.endswith(\"seed\")\n and not key.split(\"/\")[1] == \"output_options\"\n )\n\n def create_summary(self, save_to_disk: bool = False) -> List[Dict]:\n \"\"\"Returns a summary of the results and saves it in the evaluation directory if the flag argument is True.\n\n Parameters\n ----------\n save_to_disk : bool = False\n Flag for saving the summary to disk.\n\n Returns\n -------\n List[Dict]\n List containing summary dicts for each run. The summary contains:\n Scenario name, options_uuid, path to the results folder, success flag.\n \"\"\"\n self.logger.info(\"Summarizing results\")\n results = []\n\n # Get the config keys that define alterations from the bulk config\n co_keys = [\n key.lstrip(\"options_alterations/\")\n for key, value in (flatten_dictionary(self.bulk_config)).items()\n if self._check_alterations_key(key, value)\n ]\n\n for run_dir in get_run_directories(self.path):\n data = load_result(run_dir)\n options = load_options(run_dir)\n scenario = load_scenario(run_dir)\n uuid = load_uuid(run_dir)\n\n data[\"scenario\"] = scenario[\"name\"]\n # Add uuids and hashes to the results file\n data.update(uuid)\n # added the path to the results so that the folder can be found for the visualization\n data[\"path\"] = str(run_dir.resolve())\n\n # Load the altered options from the options file and append them to the results\n if co_keys:\n flat_opt = flatten_dictionary(options)\n for key in co_keys:\n name = key.split(\"/\")[-1]\n data[name] = flat_opt[key]\n\n # determine whether the run was successful or not\n data[\"success\"] = is_successful_result(data)\n\n results.append(data)\n\n # persist summary to disk\n if save_to_disk:\n path = self.path / \"results.json\"\n io.save_data(results, path)\n return results\n\n def create_result_dataframe(self, save_to_disk: bool = False) -> pd.DataFrame:\n \"\"\"Returns detailed result information including the compute options and saves them in the evaluation directory if the flag argument is True.\n\n Parameters\n ----------\n save_to_disk : bool = False\n Flag for saving the summary to disk.\n\n Returns\n -------\n pandas.DataFrame\n DataFrame generated from the individual run results. Contains for each run:\n Complete options, detailed result, uuid, scenario name.\n \"\"\"\n all_data = []\n\n for result_path, options_path, scenario_path, uuid_path in tqdm(\n zip(\n self.path.rglob(\"result.json\"),\n self.path.rglob(\"options_output.json\"),\n self.path.rglob(\"scenario_output.json\"),\n self.path.rglob(\"uuid.json\"),\n ),\n total=self.number_evaluations,\n ascii=True,\n desc=\"Generating DataFrame\",\n ):\n # open all files and extract the information\n options = pd.json_normalize(io.load_data(options_path))\n results = pd.json_normalize(io.load_data(result_path))\n uuid = pd.json_normalize(io.load_data(uuid_path))\n\n run_data = pd.concat([options, uuid, results], axis=1)\n run_data[\"scenario\"] = io.load_data(scenario_path)[\"name\"]\n all_data.append(run_data)\n\n df_all = pd.concat(all_data, axis=0)\n df_all.reset_index(drop=True, inplace=True)\n\n if save_to_disk:\n df_all.to_pickle(self.path / \"run_data.gz\", compression=\"gzip\")\n\n return df_all\n"
] | [
[
"pandas.concat"
]
] |
tzhhhh123/Stark | [
"ba59f9596b06bc687d726f991e1e7fce8af6b5a5"
] | [
"external/AR/pytracking/analysis/plot_results.py"
] | [
"import tikzplotlib\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport os\nimport torch\nimport pickle\nimport json\nfrom pytracking.evaluation.environment import env_settings\nfrom pytracking.analysis.extract_results import extract_results\n\n\ndef get_plot_draw_styles():\n plot_draw_style = [{'color': (1.0, 0.0, 0.0), 'line_style': '-'},\n {'color': (0.0, 1.0, 0.0), 'line_style': '-'},\n {'color': (0.0, 0.0, 1.0), 'line_style': '-'},\n {'color': (0.0, 0.0, 0.0), 'line_style': '-'},\n {'color': (1.0, 0.0, 1.0), 'line_style': '-'},\n {'color': (0.0, 1.0, 1.0), 'line_style': '-'},\n {'color': (0.5, 0.5, 0.5), 'line_style': '-'},\n {'color': (136.0 / 255.0, 0.0, 21.0 / 255.0), 'line_style': '-'},\n {'color': (1.0, 127.0 / 255.0, 39.0 / 255.0), 'line_style': '-'},\n {'color': (0.0, 162.0 / 255.0, 232.0 / 255.0), 'line_style': '-'},\n {'color': (0.0, 0.5, 0.0), 'line_style': '-'},\n {'color': (1.0, 0.5, 0.2), 'line_style': '-'},\n {'color': (0.1, 0.4, 0.0), 'line_style': '-'},\n {'color': (0.6, 0.3, 0.9), 'line_style': '-'},\n {'color': (0.4, 0.7, 0.1), 'line_style': '-'},\n {'color': (0.2, 0.1, 0.7), 'line_style': '-'},\n {'color': (0.7, 0.6, 0.2), 'line_style': '-'}]\n\n return plot_draw_style\n\n\ndef check_eval_data_is_valid(eval_data, trackers, dataset):\n \"\"\" Checks if the pre-computed results are valid\"\"\"\n seq_names = [s.name for s in dataset]\n seq_names_saved = eval_data['sequences']\n\n tracker_names_f = [(t.name, t.parameter_name, t.run_id) for t in trackers]\n tracker_names_f_saved = [(t['name'], t['param'], t['run_id']) for t in eval_data['trackers']]\n\n return seq_names == seq_names_saved and tracker_names_f == tracker_names_f_saved\n\n\ndef merge_multiple_runs(eval_data):\n new_tracker_names = []\n ave_success_rate_plot_overlap_merged = []\n ave_success_rate_plot_center_merged = []\n ave_success_rate_plot_center_norm_merged = []\n avg_overlap_all_merged = []\n\n ave_success_rate_plot_overlap = torch.tensor(eval_data['ave_success_rate_plot_overlap'])\n ave_success_rate_plot_center = torch.tensor(eval_data['ave_success_rate_plot_center'])\n ave_success_rate_plot_center_norm = torch.tensor(eval_data['ave_success_rate_plot_center_norm'])\n avg_overlap_all = torch.tensor(eval_data['avg_overlap_all'])\n\n trackers = eval_data['trackers']\n merged = torch.zeros(len(trackers), dtype=torch.uint8)\n for i in range(len(trackers)):\n if merged[i]:\n continue\n base_tracker = trackers[i]\n new_tracker_names.append(base_tracker)\n\n match = [t['name'] == base_tracker['name'] and t['param'] == base_tracker['param'] for t in trackers]\n match = torch.tensor(match)\n\n ave_success_rate_plot_overlap_merged.append(ave_success_rate_plot_overlap[:, match, :].mean(1))\n ave_success_rate_plot_center_merged.append(ave_success_rate_plot_center[:, match, :].mean(1))\n ave_success_rate_plot_center_norm_merged.append(ave_success_rate_plot_center_norm[:, match, :].mean(1))\n avg_overlap_all_merged.append(avg_overlap_all[:, match].mean(1))\n\n merged[match] = 1\n\n ave_success_rate_plot_overlap_merged = torch.stack(ave_success_rate_plot_overlap_merged, dim=1)\n ave_success_rate_plot_center_merged = torch.stack(ave_success_rate_plot_center_merged, dim=1)\n ave_success_rate_plot_center_norm_merged = torch.stack(ave_success_rate_plot_center_norm_merged, dim=1)\n avg_overlap_all_merged = torch.stack(avg_overlap_all_merged, dim=1)\n\n eval_data['trackers'] = new_tracker_names\n eval_data['ave_success_rate_plot_overlap'] = ave_success_rate_plot_overlap_merged.tolist()\n eval_data['ave_success_rate_plot_center'] = ave_success_rate_plot_center_merged.tolist()\n eval_data['ave_success_rate_plot_center_norm'] = ave_success_rate_plot_center_norm_merged.tolist()\n eval_data['avg_overlap_all'] = avg_overlap_all_merged.tolist()\n\n return eval_data\n\n\ndef get_tracker_display_name(tracker):\n if tracker['disp_name'] is None:\n if tracker['run_id'] is None:\n disp_name = '{}_{}'.format(tracker['name'], tracker['param'])\n else:\n disp_name = '{}_{}_{:03d}'.format(tracker['name'], tracker['param'],\n tracker['run_id'])\n else:\n disp_name = tracker['disp_name']\n\n return disp_name\n\n\ndef plot_draw_save(y, x, scores, trackers, plot_draw_styles, result_plot_path, plot_opts):\n # Plot settings\n font_size = plot_opts.get('font_size', 12)\n font_size_axis = plot_opts.get('font_size_axis', 13)\n line_width = plot_opts.get('line_width', 2)\n font_size_legend = plot_opts.get('font_size_legend', 13)\n\n plot_type = plot_opts['plot_type']\n legend_loc = plot_opts['legend_loc']\n\n xlabel = plot_opts['xlabel']\n ylabel = plot_opts['ylabel']\n xlim = plot_opts['xlim']\n ylim = plot_opts['ylim']\n\n title = plot_opts['title']\n\n matplotlib.rcParams.update({'font.size': font_size})\n matplotlib.rcParams.update({'axes.titlesize': font_size_axis})\n matplotlib.rcParams.update({'axes.titleweight': 'black'})\n matplotlib.rcParams.update({'axes.labelsize': font_size_axis})\n\n fig, ax = plt.subplots()\n\n index_sort = scores.argsort(descending=False)\n\n plotted_lines = []\n legend_text = []\n\n for id, id_sort in enumerate(index_sort):\n line = ax.plot(x.tolist(), y[id_sort, :].tolist(),\n linewidth=line_width,\n color=plot_draw_styles[index_sort.numel() - id - 1]['color'],\n linestyle=plot_draw_styles[index_sort.numel() - id - 1]['line_style'])\n\n plotted_lines.append(line[0])\n\n tracker = trackers[id_sort]\n disp_name = get_tracker_display_name(tracker)\n\n legend_text.append('{} [{:.1f}]'.format(disp_name, scores[id_sort]))\n\n ax.legend(plotted_lines[::-1], legend_text[::-1], loc=legend_loc, fancybox=False, edgecolor='black',\n fontsize=font_size_legend, framealpha=1.0)\n\n ax.set(xlabel=xlabel,\n ylabel=ylabel,\n xlim=xlim, ylim=ylim,\n title=title)\n\n ax.grid(True, linestyle='-.')\n fig.tight_layout()\n\n tikzplotlib.save('{}/{}_plot.tex'.format(result_plot_path, plot_type))\n fig.savefig('{}/{}_plot.pdf'.format(result_plot_path, plot_type), dpi=300, format='pdf', transparent=True)\n plt.draw()\n\n\ndef check_and_load_precomputed_results(trackers, dataset, report_name, force_evaluation=False, **kwargs):\n # Load data\n settings = env_settings()\n\n # Load pre-computed results\n result_plot_path = os.path.join(settings.result_plot_path, report_name)\n eval_data_path = os.path.join(result_plot_path, 'eval_data.pkl')\n\n if os.path.isfile(eval_data_path) and not force_evaluation:\n with open(eval_data_path, 'rb') as fh:\n eval_data = pickle.load(fh)\n else:\n # print('Pre-computed evaluation data not found. Computing results!')\n eval_data = extract_results(trackers, dataset, report_name, **kwargs)\n\n if not check_eval_data_is_valid(eval_data, trackers, dataset):\n # print('Pre-computed evaluation data invalid. Re-computing results!')\n eval_data = extract_results(trackers, dataset, report_name, **kwargs)\n else:\n # Update display names\n tracker_names = [{'name': t.name, 'param': t.parameter_name, 'run_id': t.run_id, 'disp_name': t.display_name}\n for t in trackers]\n eval_data['trackers'] = tracker_names\n\n return eval_data\n\n\ndef get_auc_curve(ave_success_rate_plot_overlap, valid_sequence):\n ave_success_rate_plot_overlap = ave_success_rate_plot_overlap[valid_sequence, :, :]\n auc_curve = ave_success_rate_plot_overlap.mean(0) * 100.0\n auc = auc_curve.mean(-1)\n\n return auc_curve, auc\n\n\ndef get_prec_curve(ave_success_rate_plot_center, valid_sequence):\n ave_success_rate_plot_center = ave_success_rate_plot_center[valid_sequence, :, :]\n prec_curve = ave_success_rate_plot_center.mean(0) * 100.0\n prec_score = prec_curve[:, 20]\n\n return prec_curve, prec_score\n\n\ndef plot_results(trackers, dataset, report_name, merge_results=False,\n plot_types=('success'), force_evaluation=False, **kwargs):\n \"\"\"\n Plot results for the given trackers\n\n args:\n trackers - List of trackers to evaluate\n dataset - List of sequences to evaluate\n report_name - Name of the folder in env_settings.perm_mat_path where the computed results and plots are saved\n merge_results - If True, multiple random runs for a non-deterministic trackers are averaged\n plot_types - List of scores to display. Can contain 'success',\n 'prec' (precision), and 'norm_prec' (normalized precision)\n \"\"\"\n # Load data\n settings = env_settings()\n\n plot_draw_styles = get_plot_draw_styles()\n\n # Load pre-computed results\n result_plot_path = os.path.join(settings.result_plot_path, report_name)\n eval_data = check_and_load_precomputed_results(trackers, dataset, report_name, force_evaluation, **kwargs)\n\n # Merge results from multiple runs\n if merge_results:\n eval_data = merge_multiple_runs(eval_data)\n\n tracker_names = eval_data['trackers']\n\n valid_sequence = torch.tensor(eval_data['valid_sequence'], dtype=torch.bool)\n\n print('\\nPlotting results over {} / {} sequences'.format(valid_sequence.long().sum().item(), valid_sequence.shape[0]))\n\n print('\\nGenerating plots for: {}'.format(report_name))\n\n # ******************************** Success Plot **************************************\n if 'success' in plot_types:\n ave_success_rate_plot_overlap = torch.tensor(eval_data['ave_success_rate_plot_overlap'])\n\n # Index out valid sequences\n auc_curve, auc = get_auc_curve(ave_success_rate_plot_overlap, valid_sequence)\n threshold_set_overlap = torch.tensor(eval_data['threshold_set_overlap'])\n\n success_plot_opts = {'plot_type': 'success', 'legend_loc': 'lower left', 'xlabel': 'Overlap threshold',\n 'ylabel': 'Overlap Precision [%]', 'xlim': (0, 1.0), 'ylim': (0, 100), 'title': 'Success plot'}\n plot_draw_save(auc_curve, threshold_set_overlap, auc, tracker_names, plot_draw_styles, result_plot_path, success_plot_opts)\n\n # ******************************** Precision Plot **************************************\n if 'prec' in plot_types:\n ave_success_rate_plot_center = torch.tensor(eval_data['ave_success_rate_plot_center'])\n\n # Index out valid sequences\n prec_curve, prec_score = get_prec_curve(ave_success_rate_plot_center, valid_sequence)\n threshold_set_center = torch.tensor(eval_data['threshold_set_center'])\n\n precision_plot_opts = {'plot_type': 'precision', 'legend_loc': 'lower right',\n 'xlabel': 'Location error threshold [pixels]', 'ylabel': 'Distance Precision [%]',\n 'xlim': (0, 50), 'ylim': (0, 100), 'title': 'Precision plot'}\n plot_draw_save(prec_curve, threshold_set_center, prec_score, tracker_names, plot_draw_styles, result_plot_path,\n precision_plot_opts)\n\n # ******************************** Norm Precision Plot **************************************\n if 'norm_prec' in plot_types:\n ave_success_rate_plot_center_norm = torch.tensor(eval_data['ave_success_rate_plot_center_norm'])\n\n # Index out valid sequences\n prec_curve, prec_score = get_prec_curve(ave_success_rate_plot_center_norm, valid_sequence)\n threshold_set_center_norm = torch.tensor(eval_data['threshold_set_center_norm'])\n\n norm_precision_plot_opts = {'plot_type': 'norm_precision', 'legend_loc': 'lower right',\n 'xlabel': 'Location error threshold', 'ylabel': 'Distance Precision [%]',\n 'xlim': (0, 0.5), 'ylim': (0, 100), 'title': 'Normalized Precision plot'}\n plot_draw_save(prec_curve, threshold_set_center_norm, prec_score, tracker_names, plot_draw_styles, result_plot_path,\n norm_precision_plot_opts)\n\n plt.show()\n\n\ndef generate_formatted_report(row_labels, scores, table_name=''):\n name_width = max([len(d) for d in row_labels] + [len(table_name)]) + 5\n min_score_width = 10\n\n report_text = '\\n{label: <{width}} |'.format(label=table_name, width=name_width)\n\n score_widths = [max(min_score_width, len(k) + 3) for k in scores.keys()]\n\n for s, s_w in zip(scores.keys(), score_widths):\n report_text = '{prev} {s: <{width}} |'.format(prev=report_text, s=s, width=s_w)\n\n report_text = '{prev}\\n'.format(prev=report_text)\n\n for trk_id, d_name in enumerate(row_labels):\n # display name\n report_text = '{prev}{tracker: <{width}} |'.format(prev=report_text, tracker=d_name,\n width=name_width)\n for (score_type, score_value), s_w in zip(scores.items(), score_widths):\n report_text = '{prev} {score: <{width}} |'.format(prev=report_text,\n score='{:0.2f}'.format(score_value[trk_id].item()),\n width=s_w)\n report_text = '{prev}\\n'.format(prev=report_text)\n\n return report_text\n\n\ndef print_results(trackers, dataset, report_name, merge_results=False,\n plot_types=('success'), **kwargs):\n \"\"\" Print the results for the given trackers in a formatted table\n args:\n trackers - List of trackers to evaluate\n dataset - List of sequences to evaluate\n report_name - Name of the folder in env_settings.perm_mat_path where the computed results and plots are saved\n merge_results - If True, multiple random runs for a non-deterministic trackers are averaged\n plot_types - List of scores to display. Can contain 'success' (prints AUC, OP50, and OP75 scores),\n 'prec' (prints precision score), and 'norm_prec' (prints normalized precision score)\n \"\"\"\n # Load pre-computed results\n eval_data = check_and_load_precomputed_results(trackers, dataset, report_name, **kwargs)\n\n # Merge results from multiple runs\n if merge_results:\n eval_data = merge_multiple_runs(eval_data)\n\n tracker_names = eval_data['trackers']\n valid_sequence = torch.tensor(eval_data['valid_sequence'], dtype=torch.bool)\n\n print('\\nReporting results over {} / {} sequences'.format(valid_sequence.long().sum().item(), valid_sequence.shape[0]))\n\n scores = {}\n\n # ******************************** Success Plot **************************************\n if 'success' in plot_types:\n threshold_set_overlap = torch.tensor(eval_data['threshold_set_overlap'])\n ave_success_rate_plot_overlap = torch.tensor(eval_data['ave_success_rate_plot_overlap'])\n\n # Index out valid sequences\n auc_curve, auc = get_auc_curve(ave_success_rate_plot_overlap, valid_sequence)\n scores['AUC'] = auc\n scores['OP50'] = auc_curve[:, threshold_set_overlap == 0.50]\n scores['OP75'] = auc_curve[:, threshold_set_overlap == 0.75]\n\n # ******************************** Precision Plot **************************************\n if 'prec' in plot_types:\n ave_success_rate_plot_center = torch.tensor(eval_data['ave_success_rate_plot_center'])\n\n # Index out valid sequences\n prec_curve, prec_score = get_prec_curve(ave_success_rate_plot_center, valid_sequence)\n scores['Precision'] = prec_score\n\n # ******************************** Norm Precision Plot *********************************\n if 'norm_prec' in plot_types:\n ave_success_rate_plot_center_norm = torch.tensor(eval_data['ave_success_rate_plot_center_norm'])\n\n # Index out valid sequences\n norm_prec_curve, norm_prec_score = get_prec_curve(ave_success_rate_plot_center_norm, valid_sequence)\n scores['Norm Precision'] = norm_prec_score\n\n # Print\n tracker_disp_names = [get_tracker_display_name(trk) for trk in tracker_names]\n report_text = generate_formatted_report(tracker_disp_names, scores, table_name=report_name)\n print(report_text)\n\n\ndef plot_got_success(trackers, report_name):\n \"\"\" Plot success plot for GOT-10k dataset using the json reports.\n Save the json reports from http://got-10k.aitestunion.com/leaderboard in the directory set to\n env_settings.got_reports_path\n\n The tracker name in the experiment file should be set to the name of the report file for that tracker,\n e.g. DiMP50_report_2019_09_02_15_44_25 if the report is name DiMP50_report_2019_09_02_15_44_25.json\n\n args:\n trackers - List of trackers to evaluate\n report_name - Name of the folder in env_settings.perm_mat_path where the computed results and plots are saved\n \"\"\"\n # Load data\n settings = env_settings()\n plot_draw_styles = get_plot_draw_styles()\n\n result_plot_path = os.path.join(settings.result_plot_path, report_name)\n\n auc_curve = torch.zeros((len(trackers), 101))\n scores = torch.zeros(len(trackers))\n\n # Load results\n tracker_names = []\n for trk_id, trk in enumerate(trackers):\n json_path = '{}/{}.json'.format(settings.got_reports_path, trk.name)\n\n if os.path.isfile(json_path):\n with open(json_path, 'r') as f:\n eval_data = json.load(f)\n else:\n raise Exception('Report not found {}'.format(json_path))\n\n if len(eval_data.keys()) > 1:\n raise Exception\n\n # First field is the tracker name. Index it out\n eval_data = eval_data[list(eval_data.keys())[0]]\n if 'succ_curve' in eval_data.keys():\n curve = eval_data['succ_curve']\n ao = eval_data['ao']\n elif 'overall' in eval_data.keys() and 'succ_curve' in eval_data['overall'].keys():\n curve = eval_data['overall']['succ_curve']\n ao = eval_data['overall']['ao']\n else:\n raise Exception('Invalid JSON file {}'.format(json_path))\n\n auc_curve[trk_id, :] = torch.tensor(curve) * 100.0\n scores[trk_id] = ao * 100.0\n\n tracker_names.append({'name': trk.name, 'param': trk.parameter_name, 'run_id': trk.run_id,\n 'disp_name': trk.display_name})\n\n threshold_set_overlap = torch.arange(0.0, 1.01, 0.01, dtype=torch.float64)\n\n success_plot_opts = {'plot_type': 'success', 'legend_loc': 'lower left', 'xlabel': 'Overlap threshold',\n 'ylabel': 'Overlap Precision [%]', 'xlim': (0, 1.0), 'ylim': (0, 100), 'title': 'Success plot'}\n plot_draw_save(auc_curve, threshold_set_overlap, scores, tracker_names, plot_draw_styles, result_plot_path,\n success_plot_opts)\n plt.show()\n\n\ndef print_per_sequence_results(trackers, dataset, report_name, merge_results=False,\n filter_criteria=None, **kwargs):\n \"\"\" Print per-sequence results for the given trackers. Additionally, the sequences to list can be filtered using\n the filter criteria.\n\n args:\n trackers - List of trackers to evaluate\n dataset - List of sequences to evaluate\n report_name - Name of the folder in env_settings.perm_mat_path where the computed results and plots are saved\n merge_results - If True, multiple random runs for a non-deterministic trackers are averaged\n filter_criteria - Filter sequence results which are reported. Following modes are supported\n None: No filtering. Display results for all sequences in dataset\n 'ao_min': Only display sequences for which the minimum average overlap (AO) score over the\n trackers is less than a threshold filter_criteria['threshold']. This mode can\n be used to select sequences where at least one tracker performs poorly.\n 'ao_max': Only display sequences for which the maximum average overlap (AO) score over the\n trackers is less than a threshold filter_criteria['threshold']. This mode can\n be used to select sequences all tracker performs poorly.\n 'delta_ao': Only display sequences for which the performance of different trackers vary by at\n least filter_criteria['threshold'] in average overlap (AO) score. This mode can\n be used to select sequences where the behaviour of the trackers greatly differ\n between each other.\n \"\"\"\n # Load pre-computed results\n eval_data = check_and_load_precomputed_results(trackers, dataset, report_name, **kwargs)\n\n # Merge results from multiple runs\n if merge_results:\n eval_data = merge_multiple_runs(eval_data)\n\n tracker_names = eval_data['trackers']\n valid_sequence = torch.tensor(eval_data['valid_sequence'], dtype=torch.bool)\n sequence_names = eval_data['sequences']\n avg_overlap_all = torch.tensor(eval_data['avg_overlap_all']) * 100.0\n\n # Filter sequences\n if filter_criteria is not None:\n if filter_criteria['mode'] == 'ao_min':\n min_ao = avg_overlap_all.min(dim=1)[0]\n valid_sequence = valid_sequence & (min_ao < filter_criteria['threshold'])\n elif filter_criteria['mode'] == 'ao_max':\n max_ao = avg_overlap_all.max(dim=1)[0]\n valid_sequence = valid_sequence & (max_ao < filter_criteria['threshold'])\n elif filter_criteria['mode'] == 'delta_ao':\n min_ao = avg_overlap_all.min(dim=1)[0]\n max_ao = avg_overlap_all.max(dim=1)[0]\n valid_sequence = valid_sequence & ((max_ao - min_ao) > filter_criteria['threshold'])\n else:\n raise Exception\n\n avg_overlap_all = avg_overlap_all[valid_sequence, :]\n sequence_names = [s + ' (ID={})'.format(i) for i, (s, v) in enumerate(zip(sequence_names, valid_sequence.tolist())) if v]\n\n tracker_disp_names = [get_tracker_display_name(trk) for trk in tracker_names]\n\n scores_per_tracker = {k: avg_overlap_all[:, i] for i, k in enumerate(tracker_disp_names)}\n report_text = generate_formatted_report(sequence_names, scores_per_tracker)\n\n print(report_text)\n"
] | [
[
"torch.stack",
"matplotlib.pyplot.draw",
"torch.tensor",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show",
"matplotlib.rcParams.update",
"torch.arange"
]
] |
alex9954/CenterNet-better | [
"41f2c402ecb089f563fae7201143227492f64cc6"
] | [
"dl_lib/network/generator/centernet_gt.py"
] | [
"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\n# author: [email protected]\n\nimport numpy as np\nimport torch\n\n\nclass CenterNetGT(object):\n\n @staticmethod\n def generate(config, batched_input):\n box_scale = 1 / config.MODEL.CENTERNET.DOWN_SCALE\n num_classes = config.MODEL.CENTERNET.NUM_CLASSES\n output_size = config.INPUT.OUTPUT_SIZE\n min_overlap = config.MODEL.CENTERNET.MIN_OVERLAP\n tensor_dim = config.MODEL.CENTERNET.TENSOR_DIM\n gaussian_ratio = config.MODEL.CENTERNET.GAUSSIAN_RATIO\n num_objects = config.MODEL.CENTERNET.NUM_OBJECTS\n\n scoremap_list, wh_list, reg_list, reg_mask_list, index_list, mask_point_list = [[] for i in range(6)]\n object_count_list = [torch.Tensor([0])]\n for data in batched_input:\n # img_size = (data['height'], data['width'])\n\n bbox_dict = data['instances'].get_fields()\n\n # init gt tensors\n # gt_scoremap = torch.zeros(num_classes, *output_size)\n gt_scoremap = torch.zeros(num_objects, *output_size)\n gt_wh = torch.zeros(num_objects, 2)\n # gt_reg = torch.zeros_like(gt_wh)\n # reg_mask = torch.zeros(tensor_dim)\n # gt_index = torch.zeros(tensor_dim)\n # pass\n\n boxes, classes = bbox_dict['gt_boxes'], bbox_dict['gt_classes']\n mask_point = bbox_dict['gt_masks']\n num_boxes = boxes.tensor.shape[0]\n boxes.scale(box_scale, box_scale)\n\n centers = boxes.get_centers()\n centers_int = centers.to(torch.int32)\n centers_pos = centers_int.sum(dim=-1)\n _, center_index = torch.sort(centers_pos)\n # gt_index[:num_boxes] = centers_int[..., 1] * output_size[1] + centers_int[..., 0]\n # gt_reg[:num_boxes] = centers - centers_int\n # reg_mask[:num_boxes] = 1\n\n wh = torch.zeros_like(centers)\n box_tensor = boxes.tensor\n wh[..., 0] = box_tensor[..., 2] - box_tensor[..., 0]\n wh[..., 1] = box_tensor[..., 3] - box_tensor[..., 1]\n CenterNetGT.generate_score_map(\n gt_scoremap, num_objects, wh,\n min_overlap, gaussian_ratio, mask_point, box_scale\n )\n gt_wh[:num_boxes] = wh\n\n # center_index = torch.cat([center_index, torch.zeros(num_objects - num_boxes).long()], dim=0)\n # gt_scoremap = gt_scoremap.index_select(0, center_index)\n # gt_scoremap = torch.cat([gt_scoremap, torch.zeros(num_objects - num_boxes, 128, 128)], dim=0)\n\n scoremap_list.append(gt_scoremap)\n object_count_list.append(torch.Tensor([num_boxes]))\n for i in mask_point.polygons:\n mask_point_list.append(torch.from_numpy(i[0]))\n # wh_list.append(gt_wh)\n # reg_list.append(gt_reg)\n # reg_mask_list.append(reg_mask)\n # index_list.append(gt_index)\n\n # gt_dict = {\n # \"score_map\": torch.stack(scoremap_list, dim=0),\n # \"wh\": torch.stack(wh_list, dim=0),\n # \"reg\": torch.stack(reg_list, dim=0),\n # \"reg_mask\": torch.stack(reg_mask_list, dim=0),\n # \"index\": torch.stack(index_list, dim=0),\n # }\n gt_dict = {\"score_map\": torch.stack(scoremap_list, dim=0),\n \"object_count\": torch.stack(object_count_list, dim=0),\n \"mask_point\": mask_point_list,\n }\n return gt_dict\n\n @staticmethod\n def generate_score_map(fmap, num_objects, gt_wh, min_overlap, gaussian_ratio, mask_point, scale):\n radius = CenterNetGT.get_gaussian_radius(gt_wh, min_overlap)\n radius = torch.clamp_min(radius, 0)\n radius = radius.type(torch.int).cpu().numpy()\n for i in range(radius.shape[0]):\n # channel_index = gt_class[i]\n CenterNetGT.draw_gaussian(fmap[i], mask_point.polygons[i][0],\n (radius[i] * gaussian_ratio).astype(int), scale)\n\n @staticmethod\n def get_gaussian_radius(box_size, min_overlap):\n \"\"\"\n copyed from CornerNet\n box_size (w, h), it could be a torch.Tensor, numpy.ndarray, list or tuple\n notice: we are using a bug-version, please refer to fix bug version in CornerNet\n \"\"\"\n box_tensor = torch.Tensor(box_size)\n width, height = box_tensor[..., 0], box_tensor[..., 1]\n\n a1 = 1\n b1 = (height + width)\n c1 = width * height * (1 - min_overlap) / (1 + min_overlap)\n sq1 = torch.sqrt(b1 ** 2 - 4 * a1 * c1)\n r1 = (b1 + sq1) / 2\n\n a2 = 4\n b2 = 2 * (height + width)\n c2 = (1 - min_overlap) * width * height\n sq2 = torch.sqrt(b2 ** 2 - 4 * a2 * c2)\n r2 = (b2 + sq2) / 2\n\n a3 = 4 * min_overlap\n b3 = -2 * min_overlap * (height + width)\n c3 = (min_overlap - 1) * width * height\n sq3 = torch.sqrt(b3 ** 2 - 4 * a3 * c3)\n r3 = (b3 + sq3) / 2\n\n return torch.min(r1, torch.min(r2, r3))\n\n @staticmethod\n def gaussian2D(radius, sigma=1):\n # m, n = [(s - 1.) / 2. for s in shape]\n m, n = radius\n y, x = np.ogrid[-m:m + 1, -n:n + 1]\n\n gauss = np.exp(-(x * x + y * y) / (2 * sigma * sigma))\n gauss[gauss < np.finfo(gauss.dtype).eps * gauss.max()] = 0\n return gauss\n\n @staticmethod\n def draw_gaussian(fmap, polygon, radius, scale, k=1):\n diameter = 2 * radius + 1\n gaussian = CenterNetGT.gaussian2D((radius, radius), sigma=diameter / 6)\n gaussian = torch.Tensor(gaussian)\n for x, y in zip(polygon[0::2], polygon[1::2]):\n # x, y = int(center[0]), int(center[1])\n x, y = int(x * scale), int(y * scale)\n height, width = fmap.shape[:2]\n\n left, right = min(x, radius), min(width - x, radius + 1)\n top, bottom = min(y, radius), min(height - y, radius + 1)\n\n masked_fmap = fmap[y - top:y + bottom, x - left:x + right]\n masked_gaussian = gaussian[radius - top:radius + bottom, radius - left:radius + right]\n if min(masked_gaussian.shape) > 0 and min(masked_fmap.shape) > 0:\n masked_fmap = torch.max(masked_fmap, masked_gaussian * k)\n fmap[y - top:y + bottom, x - left:x + right] = masked_fmap\n # return fmap\n"
] | [
[
"torch.min",
"torch.stack",
"torch.sort",
"torch.zeros_like",
"torch.sqrt",
"numpy.exp",
"torch.from_numpy",
"torch.max",
"torch.zeros",
"numpy.finfo",
"torch.clamp_min",
"torch.Tensor"
]
] |
ToucanToco/toucan-connectors | [
"ca7e551f728bb5350d550eb099cab569c9238550"
] | [
"tests/mysql/test_mysql.py"
] | [
"import collections\n\nimport numpy as np\nimport pandas as pd\nimport pymysql\nimport pytest\nfrom pydantic import ValidationError\nfrom pytest_mock import MockerFixture\n\nfrom toucan_connectors.common import ConnectorStatus\nfrom toucan_connectors.mysql.mysql_connector import MySQLConnector, MySQLDataSource, handle_date_0\n\n\[email protected](scope='module')\ndef mysql_server(service_container):\n def check(host_port):\n conn = pymysql.connect(\n host='127.0.0.1', port=host_port, user='ubuntu', password='ilovetoucan'\n )\n cur = conn.cursor()\n cur.execute('SELECT 1;')\n cur.close()\n conn.close()\n\n return service_container('mysql', check, pymysql.Error)\n\n\[email protected]\ndef mysql_connector(mysql_server):\n return MySQLConnector(\n name='mycon',\n host='localhost',\n port=mysql_server['port'],\n user='ubuntu',\n password='ilovetoucan',\n )\n\n\ndef test_datasource():\n with pytest.raises(ValidationError):\n MySQLDataSource(name='mycon', domain='mydomain', database='mysql_db', query='')\n\n with pytest.raises(ValueError) as exc_info:\n MySQLDataSource(name='mycon', domain='mydomain', database='mysql_db')\n assert \"'query' or 'table' must be set\" in str(exc_info.value)\n\n MySQLDataSource(name='mycon', domain='mydomain', database='mysql_db', table='mytable')\n MySQLDataSource(name='mycon', domain='mydomain', database='mysql_db', query='myquery')\n MySQLDataSource(\n name='mycon', domain='mydomain', database='mysql_db', query='myquery', table='ignored'\n )\n\n\ndef test_get_connection_params():\n connector = MySQLConnector(name='my_mysql_con', host='myhost', user='myuser')\n params = connector.get_connection_params()\n params.pop('conv')\n assert params == {\n 'host': 'myhost',\n 'user': 'myuser',\n 'charset': 'utf8mb4',\n 'cursorclass': pymysql.cursors.DictCursor,\n }\n\n connector = MySQLConnector(\n name='my_mssql_con',\n host='myhost',\n user='myuser',\n password='mypass',\n port=123,\n charset='utf8',\n connect_timeout=50,\n )\n params = connector.get_connection_params()\n params.pop('conv')\n assert params == {\n 'host': 'myhost',\n 'user': 'myuser',\n 'charset': 'utf8',\n 'cursorclass': pymysql.cursors.DictCursor,\n 'password': 'mypass',\n 'port': 123,\n 'connect_timeout': 50,\n }\n\n\ndef test_get_status_all_good(mysql_connector):\n assert mysql_connector.get_status() == ConnectorStatus(\n status=True,\n details=[\n ('Hostname resolved', True),\n ('Port opened', True),\n ('Host connection', True),\n ('Authenticated', True),\n ],\n )\n\n\ndef test_get_status_bad_host(mysql_connector):\n mysql_connector.host = 'localhot'\n status = mysql_connector.get_status()\n assert status.status is False\n assert status.details == [\n ('Hostname resolved', False),\n ('Port opened', None),\n ('Host connection', None),\n ('Authenticated', None),\n ]\n assert status.error is not None\n\n\ndef test_get_status_bad_port(mysql_connector):\n mysql_connector.port = 123000\n status = mysql_connector.get_status()\n assert status.status is False\n assert status.details == [\n ('Hostname resolved', True),\n ('Port opened', False),\n ('Host connection', None),\n ('Authenticated', None),\n ]\n assert 'port must be 0-65535.' in status.error\n\n\ndef test_get_status_bad_connection(mysql_connector, unused_port, mocker):\n mysql_connector.port = unused_port()\n mocker.patch(\n 'toucan_connectors.mysql.mysql_connector.MySQLConnector.check_port', return_value=True\n )\n status = mysql_connector.get_status()\n assert status.status is False\n assert status.details == [\n ('Hostname resolved', True),\n ('Port opened', True),\n ('Host connection', False),\n ('Authenticated', None),\n ]\n assert status.error.startswith(\"Can't connect to MySQL server on 'localhost'\")\n\n\ndef test_get_status_bad_authentication(mysql_connector):\n mysql_connector.user = 'pika'\n assert mysql_connector.get_status() == ConnectorStatus(\n status=False,\n details=[\n ('Hostname resolved', True),\n ('Port opened', True),\n ('Host connection', True),\n ('Authenticated', False),\n ],\n error=\"Access denied for user 'pika'@'172.17.0.1' (using password: YES)\",\n )\n\n\ndef test_get_df(mocker: MockerFixture):\n \"\"\"It should call the sql extractor\"\"\"\n snock = mocker.patch('pymysql.connect')\n reasq = mocker.patch('pandas.read_sql')\n mocker.patch(\n 'toucan_connectors.mysql.mysql_connector.MySQLConnector.get_foreign_key_info'\n ).return_value = []\n\n mysql_connector = MySQLConnector(\n name='mycon', host='localhost', port=22, user='ubuntu', password='ilovetoucan'\n )\n\n # With table\n data_source = MySQLDataSource(\n **{\n 'domain': 'MySQL test',\n 'type': 'external_database',\n 'name': 'Some MySQL provider',\n 'database': 'mysql_db',\n 'table': 'City',\n }\n )\n mysql_connector.get_df(data_source)\n\n conv = pymysql.converters.conversions.copy()\n conv[246] = float\n snock.assert_called_once_with(\n host='localhost',\n user='ubuntu',\n database='mysql_db',\n password='ilovetoucan',\n port=22,\n charset='utf8mb4',\n conv=conv,\n cursorclass=pymysql.cursors.DictCursor,\n )\n\n reasq.assert_called_once_with('select * from City', con=snock(), params={})\n\n # With query\n reasq.reset_mock()\n data_source = MySQLDataSource(\n **{\n 'domain': 'MySQL test',\n 'type': 'external_database',\n 'name': 'Some MySQL provider',\n 'database': 'mysql_db',\n 'query': 'select * from Country',\n }\n )\n mysql_connector.get_df(data_source)\n reasq.assert_called_once_with('select * from Country', con=snock(), params={})\n\n # With both: query should take precedence over table\n reasq.reset_mock()\n data_source = MySQLDataSource(\n **{\n 'domain': 'MySQL test',\n 'type': 'external_database',\n 'name': 'Some MySQL provider',\n 'database': 'mysql_db',\n 'table': 'City',\n 'query': 'select * from Country',\n }\n )\n mysql_connector.get_df(data_source)\n reasq.assert_called_once_with('select * from Country', con=snock(), params={})\n\n\ndef test_get_df_db_follow(mysql_connector):\n \"\"\" \" It should extract the table City and make some merge with some foreign key\"\"\"\n data_sources_spec = [\n {\n 'domain': 'MySQL test',\n 'type': 'external_database',\n 'name': 'Some MySQL provider',\n 'database': 'mysql_db',\n 'table': 'City',\n 'follow_relations': True,\n }\n ]\n\n expected_columns = [\n 'ID',\n 'Name_City',\n 'CountryCode',\n 'District',\n 'Population_City',\n 'Name_Country',\n 'Continent',\n 'Region',\n 'SurfaceArea',\n 'IndepYear',\n 'Population_Country',\n 'LifeExpectancy',\n 'GNP',\n 'GNPOld',\n 'LocalName',\n 'GovernmentForm',\n 'HeadOfState',\n 'Capital',\n 'Code2',\n ]\n\n data_source = MySQLDataSource(**data_sources_spec[0])\n df = mysql_connector.get_df(data_source)\n\n assert not df.empty\n assert len(df.columns) == 19\n\n assert collections.Counter(df.columns) == collections.Counter(expected_columns)\n assert len(df.columns) == len(expected_columns)\n\n assert len(df[df['Population_City'] > 5000000]) == 24\n\n\ndef test_get_df_db(mysql_connector):\n \"\"\" \" It should extract the table City without merges\"\"\"\n data_source_spec = {\n 'domain': 'MySQL test',\n 'type': 'external_database',\n 'name': 'Some MySQL provider',\n 'database': 'mysql_db',\n 'query': 'SELECT * FROM City WHERE Population > %(max_pop)s',\n 'parameters': {'max_pop': 5000000},\n }\n\n expected_columns = {'ID', 'Name', 'CountryCode', 'District', 'Population'}\n data_source = MySQLDataSource(**data_source_spec)\n df = mysql_connector.get_df(data_source)\n\n assert not df.empty\n assert set(df.columns) == expected_columns\n assert df.shape == (24, 5)\n\n\ndef test_get_df_forbidden_table_interpolation(mysql_connector):\n data_source_spec = {\n 'domain': 'MySQL test',\n 'type': 'external_database',\n 'name': 'Some MySQL provider',\n 'database': 'mysql_db',\n 'query': 'SELECT * FROM %(tablename)s WHERE Population > 5000000',\n 'parameters': {'tablename': 'City'},\n }\n\n data_source = MySQLDataSource(**data_source_spec)\n with pytest.raises(pd.io.sql.DatabaseError) as e:\n mysql_connector.get_df(data_source)\n assert 'interpolating table name is forbidden' in str(e.value)\n\n\ndef test_clean_response():\n \"\"\"It should replace None by np.nan and decode bytes data\"\"\"\n response = [{'name': 'fway', 'age': 13}, {'name': b'zbruh', 'age': None}]\n res = MySQLConnector.clean_response(response)\n\n assert len(res) == 2\n assert res[1]['name'] == 'zbruh'\n assert np.isnan(res[1]['age'])\n\n\ndef test_decode_df():\n \"\"\"It should decode the bytes columns\"\"\"\n df = pd.DataFrame(\n {\n 'date': [b'2013-08-01', b'2013-08-02'],\n 'country': ['France', 'Germany'],\n 'number': [1, 2],\n 'other': [b'pikka', b'chuuu'],\n 'random': [3, 4],\n }\n )\n res = MySQLConnector.decode_df(df)\n assert res['date'].tolist() == ['2013-08-01', '2013-08-02']\n assert res['other'].tolist() == ['pikka', 'chuuu']\n assert res[['country', 'number', 'random']].equals(df[['country', 'number', 'random']])\n\n df2 = df[['number', 'random']]\n res = MySQLConnector.decode_df(df2)\n assert res.equals(df2)\n\n\ndef test_get_form_empty_query(mysql_connector):\n \"\"\"It should give suggestions of the databases without changing the rest\"\"\"\n current_config = {}\n form = MySQLDataSource.get_form(mysql_connector, current_config)\n assert form['properties']['database'] == {'$ref': '#/definitions/database'}\n assert form['definitions']['database'] == {\n 'title': 'database',\n 'description': 'An enumeration.',\n 'type': 'string',\n 'enum': ['information_schema', 'mysql_db'],\n }\n\n\ndef test_get_form_query_with_good_database(mysql_connector):\n \"\"\"It should give suggestions of the collections\"\"\"\n current_config = {'database': 'mysql_db'}\n form = MySQLDataSource.get_form(mysql_connector, current_config)\n assert form['properties']['database'] == {'$ref': '#/definitions/database'}\n assert form['definitions']['database'] == {\n 'title': 'database',\n 'description': 'An enumeration.',\n 'type': 'string',\n 'enum': ['information_schema', 'mysql_db'],\n }\n assert form['properties']['table'] == {'$ref': '#/definitions/table'}\n assert form['definitions']['table'] == {\n 'title': 'table',\n 'description': 'An enumeration.',\n 'type': 'string',\n 'enum': ['City', 'Country', 'CountryLanguage'],\n }\n\n\ndef test_handle_date_0():\n date_mixed_series = [pd.Timestamp('2021-06-23 12:34:56'), '0000-00-00 00:00:00']\n df = pd.DataFrame({'DATE': date_mixed_series})\n\n # Initially, we have mixed dtype:\n assert df.dtypes.astype(str)['DATE'] == 'object'\n\n df = handle_date_0(df)\n assert df.dtypes.astype(str)['DATE'] == 'datetime64[ns]'\n assert list(df['DATE']) == [pd.Timestamp('2021-06-23 12:34:56'), pd.NaT]\n"
] | [
[
"pandas.DataFrame",
"pandas.Timestamp",
"numpy.isnan"
]
] |
xiaollz/PytorchSSD | [
"8286027b3216a53ae336b0d243d9352572de5350"
] | [
"ssds_train.py"
] | [
"from __future__ import print_function\nimport numpy as np\nimport os\nimport sys\nimport cv2\nimport random\nimport pickle\n\nimport torch\nimport torch.backends.cudnn as cudnn\nfrom torch.autograd import Variable\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nimport torch.utils.data as data\nimport torch.nn.init as init\n\nfrom tensorboardX import SummaryWriter\n\nfrom layers import *\nfrom layers.modules.multibox_loss import MultiBoxLoss2\nfrom data import BaseTransform\nfrom utils.timer import Timer\nfrom data.data_augment import preproc\nfrom data.dataset_factory import load_data\nfrom utils.config import cfg\nfrom layers.functions import Detect, PriorBox\nfrom layers.functions.detection import Detect2\nfrom models import *\n#from utils.eval_utils import *\n#from utils.visualize_utils import *\n\nclass Solver(object):\n \"\"\"\n A wrapper class for the training process\n \"\"\"\n def __init__(self):\n self.cfg = cfg\n\n # Load data\n print('===> Loading data')\n self.train_loader = load_data(cfg.dataset, 'train') if 'train' in cfg.phase else None\n self.eval_loader = load_data(cfg.dataset, 'eval') if 'eval' in cfg.phase else None\n self.test_loader = load_data(cfg.dataset, 'test') if 'test' in cfg.phase else None\n # self.visualize_loader = load_data(cfg.DATASET, 'visualize') if 'visualize' in cfg.PHASE else None\n\n # Build model\n print('===> Building model')\n self.base_trans = BaseTransform(cfg.image_size[0], cfg.network.rgb_means, cfg.network.rgb_std, (2, 0, 1))\n self.priors = PriorBox(cfg.anchor)\n self.model = eval(cfg.model+'.build_net')(cfg.image_size[0], cfg.dataset.num_classes)\n with torch.no_grad():\n self.priors = self.priors.forward()\n self.detector = Detect2(cfg.post_process)\n # Utilize GPUs for computation\n self.use_gpu = torch.cuda.is_available()\n if cfg.train.train_scope == '':\n trainable_param = self.model.parameters()\n else:\n trainable_param = self.trainable_param(cfg.train.train_scope)\n self.output_dir = os.path.join(cfg.output_dir, cfg.name, cfg.date)\n if not os.path.exists(self.output_dir):\n os.makedirs(self.output_dir)\n self.log_dir = os.path.join(self.output_dir, 'logs')\n if not os.path.exists(self.log_dir):\n os.makedirs(self.log_dir)\n self.checkpoint = cfg.train.checkpoint\n\n previous = self.find_previous()\n previous = False\n if previous:\n self.start_epoch = previous[0][-1]\n self.resume_checkpoint(previous[1][-1])\n else:\n self.start_epoch = self.initialize()\n if self.use_gpu:\n print('Utilize GPUs for computation')\n print('Number of GPU available', torch.cuda.device_count())\n self.model.cuda()\n self.priors.cuda()\n cudnn.benchmark = True\n if cfg.ngpu > 1:\n self.model = torch.nn.DataParallel(self.model, device_ids=list(range(cfg.ngpu)))\n # Print the model architecture and parameters\n #print('Model architectures:\\n{}\\n'.format(self.model))\n\n #print('Parameters and size:')\n #for name, param in self.model.named_parameters():\n # print('{}: {}'.format(name, list(param.size())))\n # print trainable scope\n print('Trainable scope: {}'.format(cfg.train.train_scope))\n self.optimizer = self.configure_optimizer(trainable_param, cfg.train.optimizer)\n self.exp_lr_scheduler = self.configure_lr_scheduler(self.optimizer, cfg.train.lr_scheduler)\n self.max_epochs = cfg.train.lr_scheduler.max_epochs\n # metric\n if cfg.network.multi_box_loss_type == 'origin':\n self.criterion = MultiBoxLoss2(cfg.matcher, self.priors, self.use_gpu)\n else:\n print('ERROR: '+cfg.multi_box_loss_type+' is not supported')\n sys.exit()\n # Set the logger\n self.writer = SummaryWriter(log_dir=self.log_dir)\n self.checkpoint_prefix = cfg.name+'_'+cfg.dataset.dataset\n\n\n def save_checkpoints(self, epochs, iters=None):\n if not os.path.exists(self.output_dir):\n os.makedirs(self.output_dir)\n if iters:\n filename = self.checkpoint_prefix + '_epoch_{:d}_iter_{:d}'.format(epochs, iters) + '.pth'\n else:\n filename = self.checkpoint_prefix + '_epoch_{:d}'.format(epochs) + '.pth'\n filename = os.path.join(self.output_dir, filename)\n torch.save(self.model.state_dict(), filename)\n with open(os.path.join(self.output_dir, 'checkpoint_list.txt'), 'a') as f:\n f.write('epoch {epoch:d}: {filename}\\n'.format(epoch=epochs, filename=filename))\n print('Wrote snapshot to: {:s}'.format(filename))\n\n # TODO: write relative cfg under the same page\n\n def resume_checkpoint(self, resume_checkpoint):\n if resume_checkpoint == '' or not os.path.isfile(resume_checkpoint):\n print((\"=> no checkpoint found at '{}'\".format(resume_checkpoint)))\n return False\n print((\"=> loading checkpoint '{:s}'\".format(resume_checkpoint)))\n checkpoint = torch.load(resume_checkpoint)\n\n # print(\"=> Weigths in the checkpoints:\")\n # print([k for k, v in list(checkpoint.items())])\n\n # remove the module in the parrallel model\n if 'module.' in list(checkpoint.items())[0][0]:\n pretrained_dict = {'.'.join(k.split('.')[1:]): v for k, v in list(checkpoint.items())}\n checkpoint = pretrained_dict\n\n resume_scope = self.cfg.train.resume_scope\n # extract the weights based on the resume scope\n if resume_scope != '':\n pretrained_dict = {}\n for k, v in list(checkpoint.items()):\n for resume_key in resume_scope.split(','):\n if resume_key in k:\n pretrained_dict[k] = v\n break\n checkpoint = pretrained_dict\n\n pretrained_dict = {k: v for k, v in checkpoint.items() if k in self.model.state_dict()}\n # print(\"=> Resume weigths:\")\n # print([k for k, v in list(pretrained_dict.items())])\n\n checkpoint = self.model.state_dict()\n\n unresume_dict = set(checkpoint)-set(pretrained_dict)\n if len(unresume_dict) != 0:\n print(\"=> UNResume weigths:\")\n print(unresume_dict)\n\n checkpoint.update(pretrained_dict)\n\n return self.model.load_state_dict(checkpoint)\n\n\n def find_previous(self):\n if not os.path.exists(os.path.join(self.output_dir, 'checkpoint_list.txt')):\n return False\n with open(os.path.join(self.output_dir, 'checkpoint_list.txt'), 'r') as f:\n lineList = f.readlines()\n epoches, resume_checkpoints = [list() for _ in range(2)]\n for line in lineList:\n epoch = int(line[line.find('epoch ') + len('epoch '): line.find(':')])\n checkpoint = line[line.find(':') + 2:-1]\n epoches.append(epoch)\n resume_checkpoints.append(checkpoint)\n return epoches, resume_checkpoints\n\n def weights_init(self, m):\n for key in m.state_dict():\n if key.split('.')[-1] == 'weight':\n if 'conv' in key:\n init.kaiming_normal(m.state_dict()[key], mode='fan_out')\n if 'bn' in key:\n m.state_dict()[key][...] = 1\n elif key.split('.')[-1] == 'bias':\n m.state_dict()[key][...] = 0\n\n\n def initialize(self):\n # TODO: ADD INIT ways\n # raise ValueError(\"Fan in and fan out can not be computed for tensor with less than 2 dimensions\")\n # for module in self.cfg.TRAIN.TRAINABLE_SCOPE.split(','):\n # if hasattr(self.model, module):\n # getattr(self.model, module).apply(self.weights_init)\n if self.checkpoint:\n print('Loading initial model weights from {:s}'.format(self.checkpoint))\n self.resume_checkpoint(self.checkpoint)\n return cfg.train.resume_epoch\n else:\n self.model.init_model(cfg.network.basenet)\n return 0\n\n\n def trainable_param(self, trainable_scope):\n for param in self.model.parameters():\n param.requires_grad = False\n\n trainable_param = []\n for module in trainable_scope.split(','):\n if hasattr(self.model, module):\n # print(getattr(self.model, module))\n for param in getattr(self.model, module).parameters():\n param.requires_grad = True\n trainable_param.extend(getattr(self.model, module).parameters())\n\n return trainable_param\n\n def train_model(self):\n\n # export graph for the model, onnx always not works\n # self.export_graph()\n\n # warm_up epoch\n for epoch in iter(range(self.start_epoch+1, self.max_epochs+1)):\n #learning rate\n sys.stdout.write('\\rEpoch {epoch:d}/{max_epochs:d}:\\n'.format(epoch=epoch, max_epochs=self.max_epochs))\n self.exp_lr_scheduler.step(epoch-cfg.train.lr_scheduler.warmup)\n if 'train' in cfg.phase:\n self.train_epoch(self.model, self.train_loader, self.optimizer, self.criterion, self.writer, epoch, self.use_gpu)\n if 'eval' in cfg.phase and epoch%cfg.test_frequency == 0:\n self.eval_epoch(self.model, self.eval_loader, self.detector, self.criterion, self.writer, epoch, self.use_gpu)\n #if 'test' in cfg.PHASE:\n # self.test_epoch(self.model, self.test_loader, self.detector, self.output_dir, self.use_gpu)\n #if 'visualize' in cfg.PHASE:\n # self.visualize_epoch(self.model, self.visualize_loader, self.priorbox, self.writer, epoch, self.use_gpu)\n\n if epoch % cfg.train.save_frequency == 0:\n self.save_checkpoints(epoch)\n\n\n def train_epoch(self, model, data_loader, optimizer, criterion, writer, epoch, use_gpu):\n model.train()\n\n epoch_size = len(data_loader)\n batch_iterator = iter(data_loader)\n\n loc_loss = 0\n conf_loss = 0\n _t = Timer()\n\n for iteration in iter(range((epoch_size))):\n with torch.no_grad():\n images, targets = next(batch_iterator)\n if use_gpu:\n images = images.cuda()\n targets = [anno.cuda() for anno in targets]\n _t.tic()\n # forward\n out = model(images)\n\n # backprop\n optimizer.zero_grad()\n loss_l, loss_c = criterion(out, targets)\n\n # some bugs in coco train2017. maybe the annonation bug.\n if loss_l.item() == float(\"Inf\"):\n continue\n\n loss = loss_l + loss_c\n loss.backward()\n optimizer.step()\n\n time = _t.toc()\n loc_loss += loss_l.item()\n conf_loss += loss_c.item()\n\n # log per iter\n log = '\\r==>Train: || {iters:d}/{epoch_size:d} in {time:.3f}s [{prograss}] || loc_loss: {loc_loss:.4f} cls_loss: {cls_loss:.4f}\\r'.format(\n prograss='#'*int(round(10*iteration/epoch_size)) + '-'*int(round(10*(1-iteration/epoch_size))), iters=iteration, epoch_size=epoch_size,\n time=time, loc_loss=loss_l.item(), cls_loss=loss_c.item())\n\n sys.stdout.write(log)\n sys.stdout.flush()\n\n # log per epoch\n sys.stdout.write('\\r')\n sys.stdout.flush()\n lr = optimizer.param_groups[0]['lr']\n log = '\\r==>Train: || Total_time: {time:.3f}s || loc_loss: {loc_loss:.4f} conf_loss: {conf_loss:.4f} || lr: {lr:.6f}\\n'.format(lr=lr,\n time=_t.total_time, loc_loss=loc_loss/epoch_size, conf_loss=conf_loss/epoch_size)\n sys.stdout.write(log)\n sys.stdout.flush()\n\n # log for tensorboard\n writer.add_scalar('Train/loc_loss', loc_loss/epoch_size, epoch)\n writer.add_scalar('Train/conf_loss', conf_loss/epoch_size, epoch)\n writer.add_scalar('Train/lr', lr, epoch)\n\n def eval_epoch(self, model, data_loader, detector, output_dir, use_gpu):\n\n model.eval()\n dataset = data_loader.dataset\n num_images = len(testset)\n num_classes = cfg.dataset.num_classes\n all_boxes = [[[] for _ in range(num_images)]\n for _ in range(num_classes)]\n\n _t = {'im_detect': Timer(), 'misc': Timer()}\n det_file = os.path.join(self.output_dir, 'detections.pkl')\n\n if cfg.test.retest:\n f = open(det_file, 'rb')\n all_boxes = pickle.load(f)\n print('Evaluating detections')\n testset.evaluate_detections(all_boxes, save_folder)\n return\n\n for i in range(num_images):\n img = testset.pull_image(i)\n with torch.no_grad():\n x = transform(img).unsqueeze(0)\n if cuda:\n x = x.to(torch.device(\"cuda\"))\n\n _t['im_detect'].tic()\n out = net(x=x, test=True) # forward pass\n boxes, scores = detector.forward(out, self.priors)\n detect_time = _t['im_detect'].toc()\n boxes = boxes[0]\n scores = scores[0]\n\n boxes = boxes.cpu().numpy()\n scores = scores.cpu().numpy()\n # scale each detection back up to the image\n scale = torch.Tensor([img.shape[1], img.shape[0],\n img.shape[1], img.shape[0]]).cpu().numpy()\n boxes *= scale\n\n _t['misc'].tic()\n\n for j in range(1, num_classes):\n inds = np.where(scores[:, j] > cfg.post_process.score_threshold)[0]\n if len(inds) == 0:\n all_boxes[j][i] = np.empty([0, 5], dtype=np.float32)\n continue\n c_bboxes = boxes[inds]\n c_scores = scores[inds, j]\n c_dets = np.hstack((c_bboxes, c_scores[:, np.newaxis])).astype(\n np.float32, copy=False)\n keep = nms(c_dets, cfg.post_process.nms, force_cpu=False)\n c_dets = c_dets[keep, :]\n all_boxes[j][i] = c_dets\n if cfg.post_process.max_per_image > 0:\n image_scores = np.hstack([all_boxes[j][i][:, -1] for j in range(1, num_classes)])\n if len(image_scores) > max_per_image:\n image_thresh = np.sort(image_scores)[-max_per_image]\n for j in range(1, num_classes):\n keep = np.where(all_boxes[j][i][:, -1] >= image_thresh)[0]\n all_boxes[j][i] = all_boxes[j][i][keep, :]\n\n nms_time = _t['misc'].toc()\n\n if i % 20 == 0:\n print('im_detect: {:d}/{:d} {:.3f}s {:.3f}s'\n .format(i + 1, num_images, detect_time, nms_time))\n _t['im_detect'].clear()\n _t['misc'].clear()\n\n with open(det_file, 'wb') as f:\n pickle.dump(all_boxes, f, pickle.HIGHEST_PROTOCOL)\n\n print('Evaluating detections')\n if args.dataset == 'VOC':\n APs, mAP = testset.evaluate_detections(all_boxes, save_folder)\n else:\n testset.evaluate_detections(all_boxes, save_folder)\n\n\n def configure_optimizer(self, trainable_param, cfg):\n if cfg.optimizer == 'sgd':\n optimizer = optim.SGD(trainable_param, lr=cfg.lr,\n momentum=cfg.momentum, weight_decay=cfg.weight_decay)\n elif cfg.optimizer == 'rmsprop':\n optimizer = optim.RMSprop(trainable_param, lr=cfg.lr,\n momentum=cfg.momentum, alpha=cfg.alpha, eps=cfg.eps, weight_decay=cfg.weight_decay)\n elif cfg.optimizer == 'adam':\n optimizer = optim.Adam(trainable_param, lr=cfg.lr,\n betas=(cfg.beta1, cfg.beta2), eps=cfg.eps, weight_decay=cfg.weight_decay)\n else:\n AssertionError('optimizer can not be recognized.')\n return optimizer\n\n\n def configure_lr_scheduler(self, optimizer, cfg):\n if cfg.lr_decay_type == 'multi-step':\n scheduler = lr_scheduler.MultiStepLR(optimizer, milestones=cfg.steps, gamma=cfg.gamma)\n elif cfg.lr_decay_type == 'exponential':\n scheduler = lr_scheduler.ExponentialLR(optimizer, gamma=cfg.gamma)\n elif cfg.lr_decay_type == 'cos':\n scheduler = lr_scheduler.CosineAnnealingLR(optimizer, T_max=cfg.max_epochs)\n else:\n AssertionError('scheduler can not be recognized.')\n return scheduler\n\n #TODO: export graph\n def export_graph(self):\n pass\n\n\ndef train_model():\n s = Solver()\n s.train_model()\n return True\n\n"
] | [
[
"torch.optim.lr_scheduler.CosineAnnealingLR",
"torch.optim.lr_scheduler.ExponentialLR",
"torch.optim.SGD",
"torch.load",
"numpy.empty",
"torch.no_grad",
"torch.cuda.device_count",
"torch.optim.Adam",
"numpy.hstack",
"torch.cuda.is_available",
"torch.optim.lr_scheduler.MultiStepLR",
"numpy.sort",
"numpy.where",
"torch.device",
"torch.optim.RMSprop",
"torch.Tensor"
]
] |
ktaebum/npex_tvm | [
"b7c0f12bbc3779f9041ff129019134a055b2dcd4"
] | [
"topi/tests/python/test_topi_transform.py"
] | [
"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"Test code for broadcasting operators.\"\"\"\nimport numpy as np\nimport tvm\nimport topi\nimport topi.testing\n\nfrom common import get_all_backend\n\ndef verify_feature_flatten(in_shape, KH, KW, S):\n A = tvm.placeholder(shape=in_shape, name=\"A\")\n B = topi.nn.feature_flatten(A, KH, KW, S)\n N, C, H, W = A.shape\n N = int(N)\n C = int(C)\n H = int(H)\n W = int(W)\n OH = (H - KH) // S + 1\n OW = (W - KW) // S + 1\n out_shape = (N * OH * OW, C * KH * KW)\n\n def check_device(device):\n ctx = tvm.context(device, 0)\n if not ctx.exist:\n print(\"Skip because %s is not enabled\" % device)\n return\n print(\"Running on target: %s\" % device)\n\n with tvm.target.create(device):\n s = topi.generic.schedule_injective(B)\n\n foo = tvm.build(s, [A, B], device, name=\"feature_flatten\")\n data_npy = np.random.uniform(size=in_shape).astype(A.dtype)\n out_npy = topi.testing.feature_flatten_python(data_npy, OH, OW, KH, KW, S)\n data_nd = tvm.nd.array(data_npy, ctx)\n out_nd = tvm.nd.array(np.empty(out_shape).astype(B.dtype), ctx)\n foo(data_nd, out_nd)\n tvm.testing.assert_allclose(out_nd.asnumpy(), out_npy)\n\n for device in get_all_backend():\n check_device(device)\n\ndef verify_flatten(in_shape):\n A = tvm.placeholder(shape=in_shape, name=\"A\")\n B = topi.nn.flatten(A)\n dim = 1\n for i in range(1, len(in_shape)):\n dim *= in_shape[i]\n\n out_shape = (in_shape[0], dim)\n def check_device(device):\n ctx = tvm.context(device, 0)\n if not ctx.exist:\n print(\"Skip because %s is not enabled\" % device)\n return\n print(\"Running on target: %s\" % device)\n with tvm.target.create(device):\n s = topi.generic.schedule_injective(B)\n foo = tvm.build(s, [A, B], device, name=\"flatten\")\n data_npy = np.random.uniform(size=in_shape).astype(A.dtype)\n out_npy = data_npy.reshape(out_shape)\n data_nd = tvm.nd.array(data_npy, ctx)\n out_nd = tvm.nd.array(np.empty(out_shape).astype(B.dtype), ctx)\n foo(data_nd, out_nd)\n tvm.testing.assert_allclose(out_nd.asnumpy(), out_npy)\n\n for device in get_all_backend():\n check_device(device)\n\n\ndef verify_expand_dims(in_shape, out_shape, axis, num_newaxis):\n A = tvm.placeholder(shape=in_shape, name=\"A\")\n B = topi.expand_dims(A, axis, num_newaxis)\n def check_device(device):\n ctx = tvm.context(device, 0)\n if not ctx.exist:\n print(\"Skip because %s is not enabled\" % device)\n return\n print(\"Running on target: %s\" % device)\n with tvm.target.create(device):\n s = topi.generic.schedule_broadcast(B)\n foo = tvm.build(s, [A, B], device, name=\"expand_dims\")\n data_npy = np.random.uniform(size=in_shape).astype(A.dtype)\n out_npy = data_npy.reshape(out_shape)\n data_nd = tvm.nd.array(data_npy, ctx)\n out_nd = tvm.nd.array(np.empty(out_shape).astype(B.dtype), ctx)\n foo(data_nd, out_nd)\n tvm.testing.assert_allclose(out_nd.asnumpy(), out_npy)\n\n for device in get_all_backend():\n check_device(device)\n\n\ndef verify_reinterpret(in_shape, in_dtype, out_dtype, generator):\n A = tvm.placeholder(shape=in_shape, name=\"A\", dtype=in_dtype)\n B = topi.reinterpret(A, out_dtype)\n def check_device(device):\n ctx = tvm.context(device, 0)\n if not ctx.exist:\n print(\"Skip because %s is not enabled\" % device)\n return\n print(\"Running on target: %s\" % device)\n with tvm.target.create(device):\n s = topi.generic.schedule_elemwise(B)\n foo = tvm.build(s, [A, B], device, name=\"reinterpret\")\n data_npy = generator(in_shape).astype(in_dtype)\n out_npy = data_npy.view(B.dtype)\n data_nd = tvm.nd.array(data_npy, ctx)\n out_nd = tvm.nd.array(np.empty(in_shape).astype(B.dtype), ctx)\n foo(data_nd, out_nd)\n np.testing.assert_equal(out_nd.asnumpy(), out_npy)\n\n for device in get_all_backend():\n check_device(device)\n\n\ndef verify_transpose(in_shape, axes):\n A = tvm.placeholder(shape=in_shape, name=\"A\")\n B = topi.transpose(A, axes)\n def check_device(device):\n ctx = tvm.context(device, 0)\n if not ctx.exist:\n print(\"Skip because %s is not enabled\" % device)\n return\n print(\"Running on target: %s\" % device)\n with tvm.target.create(device):\n s = topi.generic.schedule_injective(B)\n foo = tvm.build(s, [A, B], device, name=\"transpose\")\n data_npy = np.arange(np.prod(in_shape)).reshape(in_shape).astype(A.dtype)\n out_npy = data_npy.transpose(axes)\n data_nd = tvm.nd.array(data_npy, ctx)\n out_nd = tvm.nd.empty(out_npy.shape, ctx=ctx, dtype=B.dtype)\n foo(data_nd, out_nd)\n tvm.testing.assert_allclose(out_nd.asnumpy(), out_npy)\n\n for device in get_all_backend():\n check_device(device)\n\n\ndef verify_reshape(src_shape, dst_shape):\n A = tvm.placeholder(shape=src_shape, name=\"A\")\n B = topi.reshape(A, dst_shape)\n def check_device(device):\n ctx = tvm.context(device, 0)\n if not ctx.exist:\n print(\"Skip because %s is not enabled\" % device)\n return\n print(\"Running on target: %s\" % device)\n with tvm.target.create(device):\n s = topi.generic.schedule_injective(B)\n foo = tvm.build(s, [A, B], device, name=\"reshape\")\n data_npy = np.random.normal(size=src_shape).astype(A.dtype)\n out_npy = np.reshape(data_npy, newshape=dst_shape)\n data_nd = tvm.nd.array(data_npy, ctx)\n out_nd = tvm.nd.empty(dst_shape, ctx=ctx, dtype=B.dtype)\n foo(data_nd, out_nd)\n tvm.testing.assert_allclose(out_nd.asnumpy(), out_npy)\n\n for device in get_all_backend():\n check_device(device)\n\n\ndef verify_squeeze(src_shape, axis):\n A = tvm.placeholder(shape=src_shape, name=\"A\")\n B = topi.squeeze(A, axis=axis)\n def check_device(device):\n ctx = tvm.context(device, 0)\n if not ctx.exist:\n print(\"Skip because %s is not enabled\" % device)\n return\n print(\"Running on target: %s\" % device)\n with tvm.target.create(device):\n s = topi.generic.schedule_injective(B)\n\n foo = tvm.build(s, [A, B], device, name=\"squeeze\")\n data_npy = np.random.normal(size=src_shape).astype(A.dtype)\n out_npy = np.squeeze(data_npy, axis=axis)\n data_nd = tvm.nd.array(data_npy, ctx)\n out_nd_shape = out_npy.shape\n out_nd = tvm.nd.empty(out_nd_shape, ctx=ctx, dtype=B.dtype)\n foo(data_nd, out_nd)\n tvm.testing.assert_allclose(out_nd.asnumpy(), out_npy)\n\n for device in get_all_backend():\n check_device(device)\n\ndef verify_concatenate(shapes, axis):\n tensor_l = []\n for i, shape in enumerate(shapes):\n tensor_l.append(tvm.placeholder(shape, name=\"A\" + str(i)))\n out_tensor = topi.concatenate(a_tuple=tensor_l, axis=axis)\n def check_device(device):\n ctx = tvm.context(device, 0)\n if not ctx.exist:\n print(\"Skip because %s is not enabled\" % device)\n return\n print(\"Running on target: %s\" % device)\n with tvm.target.create(device):\n s = topi.generic.schedule_concatenate(out_tensor)\n\n foo = tvm.build(s, tensor_l + [out_tensor], device, name=\"concatenate\")\n data_npys = [np.random.normal(size=shape).astype(tensor_l[0].dtype) for shape in shapes]\n out_npy = np.concatenate(data_npys, axis=axis)\n data_nds = [tvm.nd.array(data_npy, ctx) for data_npy in data_npys]\n out_nd = tvm.nd.empty(out_npy.shape, ctx=ctx, dtype=out_tensor.dtype)\n foo(*(data_nds + [out_nd]))\n tvm.testing.assert_allclose(out_nd.asnumpy(), out_npy)\n\n for device in get_all_backend():\n check_device(device)\n\ndef verify_stack(shapes, axis):\n tensor_l = []\n for i, shape in enumerate(shapes):\n tensor_l.append(tvm.placeholder(shape, name=\"A\" + str(i)))\n out_tensor = topi.stack(tensor_l, axis)\n def check_device(device):\n ctx = tvm.context(device, 0)\n if not ctx.exist:\n print(\"Skip because %s is not enabled\" % device)\n return\n print(\"Running on target: %s\" % device)\n with tvm.target.create(device):\n s = topi.generic.schedule_broadcast(out_tensor)\n\n foo = tvm.build(s, tensor_l + [out_tensor], device, name=\"stack\")\n data_npys = [np.random.normal(size=shape).astype(tensor_l[0].dtype) for shape in shapes]\n out_npy = np.stack(data_npys, axis=axis)\n data_nds = [tvm.nd.array(data_npy, ctx) for data_npy in data_npys]\n out_nd = tvm.nd.empty(out_npy.shape, ctx=ctx, dtype=out_tensor.dtype)\n foo(*(data_nds + [out_nd]))\n tvm.testing.assert_allclose(out_nd.asnumpy(), out_npy)\n\n for device in get_all_backend():\n check_device(device)\n\n\ndef verify_split(src_shape, indices_or_sections, axis):\n A = tvm.placeholder(shape=src_shape, name=\"A\")\n tensor_l = topi.split(A, indices_or_sections, axis=axis)\n def check_device(device):\n ctx = tvm.context(device, 0)\n if not ctx.exist:\n print(\"Skip because %s is not enabled\" % device)\n return\n print(\"Running on target: %s\" % device)\n with tvm.target.create(device):\n s = topi.generic.schedule_injective(tensor_l)\n\n foo = tvm.build(s, [A] + list(tensor_l), device, name=\"split\")\n data_npy = np.random.normal(size=src_shape).astype(A.dtype)\n out_npys = np.split(data_npy, indices_or_sections, axis=axis)\n data_nd = tvm.nd.array(data_npy, ctx)\n out_nds = [tvm.nd.empty(out_npy.shape, ctx=ctx, dtype=tensor_l[0].dtype) for out_npy in out_npys]\n foo(*([data_nd] + out_nds))\n for out_nd, out_npy in zip(out_nds, out_npys):\n tvm.testing.assert_allclose(out_nd.asnumpy(), out_npy)\n\n for device in get_all_backend():\n check_device(device)\n\n\ndef verify_expand_like(in_shape, out_shape, axis):\n A = tvm.placeholder(shape=in_shape, name=\"A\")\n B = tvm.placeholder(shape=out_shape, name=\"B\")\n C = topi.expand_like(A, B, axis)\n s = tvm.create_schedule([C.op])\n\n def check_device(device):\n if not tvm.module.enabled(device):\n print(\"Skip because %s is not enabled\" % device)\n return\n print(\"Running on target: %s\" % device)\n\n ctx = tvm.context(device, 0)\n f = tvm.build(s, [A, B, C], device, name=\"expand_like\")\n input = np.random.uniform(size=in_shape).astype(A.dtype)\n tvm_input = tvm.nd.array(input, ctx)\n\n odim = len(out_shape)\n real_axis = [x if x >= 0 else x + odim for x in axis]\n real_axis = sorted(real_axis)\n for x in real_axis:\n input = np.expand_dims(input, x).astype(A.dtype)\n for x in real_axis:\n input = np.concatenate([input]*out_shape[x], axis=x).astype(A.dtype)\n assert input.shape == out_shape\n\n tvm_shape_like = tvm.nd.array(np.zeros(out_shape).astype(B.dtype), ctx)\n out = tvm.nd.array(np.zeros(out_shape).astype(A.dtype), ctx)\n f(tvm_input, tvm_shape_like, out)\n tvm.testing.assert_allclose(out.asnumpy(), input)\n\n for device in [\"llvm\"]:\n check_device(device)\n\ndef verify_flip(in_shape, axis):\n A = tvm.placeholder(shape=in_shape, name=\"A\")\n B = topi.flip(A, axis) + 1\n def check_device(device):\n ctx = tvm.context(device, 0)\n if not ctx.exist:\n print(\"Skip because %s is not enabled\" % device)\n return\n print(\"Running on target: %s\" % device)\n with tvm.target.create(device):\n s = topi.generic.schedule_injective(B)\n\n foo = tvm.build(s, [A, B], device, name=\"reverse\")\n x_np = np.random.uniform(size=in_shape).astype(A.dtype)\n out_npy = np.flip(x_np, axis) + 1\n data_nd = tvm.nd.array(x_np, ctx)\n out_nd = tvm.nd.empty(out_npy.shape, ctx=ctx, dtype=A.dtype)\n foo(data_nd, out_nd)\n tvm.testing.assert_allclose(out_nd.asnumpy(), out_npy)\n\n for device in [\"llvm\", \"cuda\", \"opencl\", \"sdaccel\", \"aocl_sw_emu\"]:\n check_device(device)\n\ndef verify_take(src_shape, indices_src, axis=None, mode=\"clip\"):\n src_dtype = \"float32\"\n indices_dtype = \"int32\"\n indices_src = np.array(indices_src, dtype=indices_dtype)\n A = tvm.placeholder(shape=src_shape, dtype=src_dtype, name=\"A\")\n indices = tvm.placeholder(shape=indices_src.shape, dtype=indices_dtype, name=\"indices\")\n if axis is None:\n out_tensor = topi.take(a=A, indices=indices, mode=mode)\n else:\n out_tensor = topi.take(a=A, indices=indices, axis=axis, mode=mode)\n\n def check_device(device):\n ctx = tvm.context(device, 0)\n if not ctx.exist:\n print(\"Skip because %s is not enabled\" % device)\n return\n print(\"Running on target: %s\" % device)\n with tvm.target.create(device):\n s = topi.generic.schedule_injective(out_tensor)\n\n foo = tvm.build(s, [A] + [indices] + [out_tensor] , device, name=\"take\")\n shape_size = 1\n for i in range(len(src_shape)):\n shape_size = shape_size * src_shape[i]\n data_npy = np.arange(shape_size, dtype=src_dtype).reshape((src_shape))\n\n if axis is None:\n np_mode = \"raise\" if mode == \"fast\" else mode\n out_npys = np.take(data_npy, indices_src, mode=np_mode)\n else:\n np_mode = \"raise\" if mode == \"fast\" else mode\n out_npys = np.take(data_npy, indices_src, axis=axis, mode=np_mode)\n data_nd = tvm.nd.array(data_npy, ctx)\n indices_nd = tvm.nd.array(indices_src, ctx)\n out_nd = tvm.nd.empty(out_npys.shape, ctx=ctx, dtype=src_dtype)\n foo(data_nd, indices_nd, out_nd)\n tvm.testing.assert_allclose(out_nd.asnumpy(), out_npys)\n\n for device in [\"llvm\", \"opencl\", \"sdaccel\", \"aocl_sw_emu\"]:\n check_device(device)\n\ndef verify_strided_slice(in_shape, begin, end, strides=None):\n A = tvm.placeholder(shape=in_shape, name=\"A\")\n strides = [1,1,1] if strides is None else strides\n B = topi.strided_slice(A, begin, end, strides) + 1\n\n def check_device(device):\n ctx = tvm.context(device, 0)\n if not ctx.exist:\n print(\"Skip because %s is not enabled\" % device)\n return\n print(\"Running on target: %s\" % device)\n with tvm.target.create(device):\n s = topi.generic.schedule_injective(B)\n\n foo = tvm.build(s, [A, B], device, name=\"stride_slice\")\n x_np = np.random.uniform(size=in_shape).astype(A.dtype)\n out_npy = topi.testing.strided_slice_python(\n x_np, begin, end, strides) + 1\n data_nd = tvm.nd.array(x_np, ctx)\n out_nd = tvm.nd.empty(out_npy.shape, ctx=ctx, dtype=A.dtype)\n foo(data_nd, out_nd)\n tvm.testing.assert_allclose(out_nd.asnumpy(), out_npy)\n\n for device in [\"llvm\", \"opencl\", \"sdaccel\", \"aocl_sw_emu\"]:\n check_device(device)\n\ndef verify_gather_nd(src_shape, indices_src, indices_dtype):\n src_dtype = \"float32\"\n indices_src = np.array(indices_src, dtype=indices_dtype)\n A = tvm.placeholder(shape=src_shape, dtype=src_dtype, name=\"A\")\n indices = tvm.placeholder(shape=indices_src.shape, dtype=indices_dtype, name=\"indices\")\n out_tensor = topi.gather_nd(a=A, indices=indices)\n\n def check_device(device):\n ctx = tvm.context(device, 0)\n if not ctx.exist:\n print(\"Skip because %s is not enabled\" % device)\n return\n print(\"Running on target: %s\" % device)\n with tvm.target.create(device):\n s = topi.generic.schedule_injective(out_tensor)\n\n func = tvm.build(s, [A, indices, out_tensor] , device, name=\"take\")\n shape_size = 1\n for i in range(len(src_shape)):\n shape_size = shape_size * src_shape[i]\n data_npy = np.arange(shape_size, dtype=src_dtype).reshape((src_shape))\n out_npys = topi.testing.gather_nd_python(data_npy, indices_src)\n\n data_nd = tvm.nd.array(data_npy, ctx)\n indices_nd = tvm.nd.array(indices_src, ctx)\n out_nd = tvm.nd.empty(out_npys.shape, ctx=ctx, dtype=src_dtype)\n func(data_nd, indices_nd, out_nd)\n tvm.testing.assert_allclose(out_nd.asnumpy(), out_npys)\n\n for device in get_all_backend():\n check_device(device)\n\ndef verify_arange(start, stop, step):\n if start is None and step is None:\n A = topi.arange(stop)\n a_np = np.arange(stop)\n elif start is None:\n A = topi.arange(stop, step=step)\n a_np = np.arange(stop, step=step)\n elif step is None:\n A = topi.arange(start, stop)\n a_np = np.arange(start, stop)\n else:\n A = topi.arange(start, stop, step)\n a_np = np.arange(start, stop, step)\n\n def check_device(device):\n ctx = tvm.context(device, 0)\n if not ctx.exist:\n print(\"Skip because %s is not enabled\" % device)\n return\n print(\"Running on target: %s\" % device)\n with tvm.target.create(device):\n s = topi.generic.schedule_injective(A)\n f = tvm.build(s, [A], device, name=\"arange\")\n a_nd = tvm.nd.empty(a_np.shape, dtype='float32', ctx=ctx)\n f(a_nd)\n tvm.testing.assert_allclose(a_nd.asnumpy(), a_np)\n\n for device in get_all_backend():\n check_device(device)\n\ndef verify_repeat(in_shape, repeats, axis):\n A = tvm.placeholder(shape=in_shape, name=\"A\")\n B = topi.repeat(A, repeats, axis)\n def check_device(device):\n ctx = tvm.context(device, 0)\n if not ctx.exist:\n print(\"Skip because %s is not enabled\" % device)\n return\n print(\"Running on target: %s\" % device)\n with tvm.target.create(device):\n s = topi.generic.schedule_broadcast(B)\n foo = tvm.build(s, [A, B], device, name=\"repeat\")\n data_npy = np.random.uniform(size=in_shape).astype(A.dtype)\n out_npy = np.repeat(data_npy, repeats, axis)\n data_nd = tvm.nd.array(data_npy, ctx)\n out_nd = tvm.nd.array(np.empty(out_npy.shape).astype(B.dtype), ctx)\n foo(data_nd, out_nd)\n tvm.testing.assert_allclose(out_nd.asnumpy(), out_npy)\n\n for device in get_all_backend():\n check_device(device)\n\ndef verify_tile(in_shape, reps):\n A = tvm.placeholder(shape=in_shape, name=\"A\")\n B = topi.tile(A, reps)\n def check_device(device):\n ctx = tvm.context(device, 0)\n if not ctx.exist:\n print(\"Skip because %s is not enabled\" % device)\n return\n print(\"Running on target: %s\" % device)\n with tvm.target.create(device):\n s = topi.generic.schedule_broadcast(B)\n foo = tvm.build(s, [A, B], device, name=\"tile\")\n data_npy = np.random.uniform(size=in_shape).astype(A.dtype)\n out_npy = np.tile(data_npy, reps)\n data_nd = tvm.nd.array(data_npy, ctx)\n out_nd = tvm.nd.array(np.empty(out_npy.shape).astype(B.dtype), ctx)\n foo(data_nd, out_nd)\n tvm.testing.assert_allclose(out_nd.asnumpy(), out_npy)\n\n for device in get_all_backend():\n check_device(device)\n\ndef verify_where(in_shape):\n Cond = tvm.placeholder(shape=in_shape, name=\"cond\")\n dtype = Cond.dtype\n A = tvm.placeholder(shape=in_shape, name=\"A\")\n B = tvm.placeholder(shape=in_shape, name=\"B\")\n C = topi.where(Cond, A, B)\n def check_device(device):\n ctx = tvm.context(device, 0)\n if not ctx.exist:\n print(\"Skip because %s is not enabled\" % device)\n return\n print(\"Running on target: %s\" % device)\n with tvm.target.create(device):\n s = topi.generic.schedule_broadcast(C)\n f = tvm.build(s, [Cond, A, B, C], device, name=\"where\")\n cond_npy = np.random.uniform(low=-1, high=1, size=in_shape).astype(dtype)\n x_npy = np.random.uniform(size=in_shape).astype(dtype)\n y_npy = np.random.uniform(size=in_shape).astype(dtype)\n out_npy = np.where(cond_npy, x_npy, y_npy)\n cond_nd = tvm.nd.array(cond_npy, ctx)\n x_nd = tvm.nd.array(x_npy, ctx)\n y_nd = tvm.nd.array(y_npy, ctx)\n out_nd = tvm.nd.array(np.empty(out_npy.shape).astype(C.dtype), ctx)\n f(cond_nd, x_nd, y_nd, out_nd)\n tvm.testing.assert_allclose(out_nd.asnumpy(), out_npy)\n\n for device in get_all_backend():\n check_device(device)\n\ndef test_feature_flatten():\n verify_feature_flatten((1, 3, 5, 5), 2, 2, 1)\n verify_feature_flatten((2, 5, 7, 7), 3, 3, 1)\n verify_feature_flatten((10, 10, 6, 8), 2, 4, 1)\n\ndef test_flatten():\n verify_flatten((3, 4, 3))\n\ndef test_strided_slice():\n verify_strided_slice((3, 4, 3), [0, 0, 0], [4, -5, 4], [1, -1, 2])\n verify_strided_slice((3, 4, 3), [1, 1, 0], [4, 4, 3], [2, 1, 1])\n verify_strided_slice((3, 4, 3), [1, -1, 0], [4, -5, 3], [2, -1, 1])\n verify_strided_slice((3, 4, 3), [1, 0, 0], [2, 2, 3], [1, 1, 2])\n verify_strided_slice((3, 4, 3), [1, -1, 0], [2, -3, 3], [1, -1, 1])\n verify_strided_slice((3, 4, 3), [1, 1, 0], [4, 4, 3])\n\ndef test_expand_dims():\n verify_expand_dims((3, 10), (3, 10, 1, 1), 2, 2)\n verify_expand_dims((3, 10), (1, 3, 10), -3, 1)\n\n\ndef test_reinterpret():\n verify_reinterpret((1000,), \"float32\", \"int32\",\n lambda shape: np.random.randn(*shape) * 1000)\n verify_reinterpret((1000,), \"float16\", \"int16\",\n lambda shape: np.random.randn(*shape) * 100)\n verify_reinterpret((1000,), \"int16\", \"uint16\",\n lambda shape: np.random.randint(-1000, 1000, size=shape))\n verify_reinterpret((1000,), \"uint32\", \"int32\",\n lambda shape: np.random.randint(0, 2 ** 32 - 1, size=shape))\n verify_reinterpret((1000,), \"uint32\", \"int32\",\n lambda shape: np.random.randint(0, 2 ** 32 - 1, size=shape))\n\n\ndef test_transpose():\n verify_transpose((3, 10, 2), (1, 0, 2))\n verify_transpose((3, 10, 5), (2, 0, 1))\n verify_transpose((3, 10), None)\n\n\ndef test_reshape():\n verify_reshape((1, 2, 3, 4), (2, 3, 4))\n verify_reshape((4, 2, 3, 4), (2, 4, 12))\n verify_reshape((4, 2, 3, 4), (2, 48))\n verify_reshape((16, ), (2, 2, 2, 2))\n\n\ndef test_where():\n verify_where((1, 2, 3, 4))\n\n\ndef test_squeeze():\n verify_squeeze((1, 2, 3, 4), 0)\n verify_squeeze((1, 2, 1, 4), None)\n verify_squeeze((1, 1, 1, 4), (1, 2))\n verify_squeeze((1, 1, 1, 1), None)\n\n # a special case to trigger inline let expression\n A = tvm.placeholder((2,), 'float32', 'A')\n E = topi.squeeze(A)\n C = tvm.compute((1,), lambda i: E[(2 * A[0] - 1).astype('int32')])\n for device in ['cuda', 'opencl']:\n ctx = tvm.context(device, 0)\n if ctx.exist:\n with tvm.target.create(device):\n s = topi.generic.schedule_injective(C)\n func = tvm.build(s, [A, C])\n a = tvm.nd.array(np.array((1, 2)).astype('float32'), ctx=ctx)\n c = tvm.nd.empty((1,), dtype='float32', ctx=ctx)\n func(a, c)\n assert c.asnumpy()[0] == 2\n\n\ndef test_concatenate():\n verify_concatenate([(2,), (2,), (2,)], -1)\n verify_concatenate([(2, 3, 4), (2, 2, 4), (2, 5, 4)], 1)\n verify_concatenate([(1, 2, 4), (1, 2, 3), (1, 2, 7), (1, 2, 8), (1, 2, 1)], -1)\n verify_concatenate([(5, 6, 7, 3),\n (16, 6, 7, 3),\n (12, 6, 7, 3),\n (8, 6, 7, 3),\n (2, 6, 7, 3)], 0)\n verify_concatenate([(1, 14400), (1, 2400), (1, 640), (1, 240)], 1)\n\n\ndef test_stack():\n verify_stack([(2,), (2,), (2,)], -1)\n verify_stack([(2,), (2,), (2,)], 1)\n verify_stack([(2,), (2,), (2,)], 0)\n verify_stack([(2, 2, 4), (2, 2, 4), (2, 2, 4)], 1)\n verify_stack([(2, 2, 3, 4), (2, 2, 3, 4), (2, 2, 3, 4), (2, 2, 3, 4)], -1)\n\n\ndef test_split():\n verify_split((2, 12, 3), 3, 1)\n verify_split((2, 12, 3), [2, 4], 1)\n verify_split((10, 12, 24), [5, 7, 9], -1)\n\ndef test_flip():\n verify_flip((3, 4, 3), 1)\n verify_flip((3, 4, 3), 0)\n verify_flip((3, 4, 3), 2)\n verify_flip((3, 4, 3), -1)\n verify_flip((3, 4, 3), -3)\n verify_flip((3, 4, 3), -2)\n\ndef test_expand_like():\n verify_expand_like((3,), (2, 3), [0])\n verify_expand_like((2,), (2, 3), [1])\n verify_expand_like((3, 4), (3, 5, 4), [1])\n verify_expand_like((5, 7), (5, 6, 7, 8), [1, 3])\n\ndef test_take():\n verify_take((4,), [1])\n verify_take((4,), [[0,1,2,3]])\n verify_take((3,3,3), [[11,25]])\n verify_take((4,), [[0,1],[2,3]])\n verify_take((4,), [1], 0)\n verify_take((2,2), [[[1,0],[0,1]]], 0)\n verify_take((2,2), [[[1,0],[0,1]]], 1)\n verify_take((4,3,5,6), [[2,1,0,0]], -2)\n verify_take((3,4), [-5, 20])\n verify_take((3,4), [-5, 20], mode=\"wrap\")\n verify_take((3,4), [-1, 2], axis=0)\n verify_take((3,4), [-1, 2], axis=0, mode=\"wrap\")\n verify_take((3,4), [-1, 2], axis=1)\n verify_take((3,4), [-1, 2], axis=1, mode=\"wrap\")\n verify_take((3,3,3), [[11,25]], mode=\"fast\")\n verify_take((3,4), [0, 2], axis=0, mode=\"fast\")\n verify_take((3,4), [0, 2], axis=1, mode=\"fast\")\n\ndef test_gather_nd():\n for indices_dtype in ['int32', 'float32']:\n verify_gather_nd((4,), [[1.8]], indices_dtype)\n verify_gather_nd((4,), [[1, 3, 2]], indices_dtype)\n verify_gather_nd((2, 3), [[1]], indices_dtype)\n verify_gather_nd((2, 3), [[1], [0]], indices_dtype)\n verify_gather_nd((2, 3), [[1, 0], [0, 2]], indices_dtype)\n verify_gather_nd((2, 3, 4), [[1, 0], [0, 2]], indices_dtype)\n verify_gather_nd((2, 3, 4), [[1, 0], [0, 2], [3, 1]], indices_dtype)\n verify_gather_nd((2, 3, 4), [[[1, 0], [0, 1]], [[0, 2], [1, 2]],\n [[3, 1], [0, 2]]], indices_dtype)\n verify_gather_nd((2, 3, 4, 5), [[1, 0], [0, 2]], indices_dtype)\n verify_gather_nd((2, 3, 4, 5), [[1, 0], [2, 1], [3, 2], [4, 2]],\n indices_dtype)\n\ndef test_arange():\n verify_arange(None, 20, None)\n verify_arange(None, 20, 2)\n verify_arange(1, 20, None)\n verify_arange(1, 20, 2)\n verify_arange(1, 20, 1.5)\n verify_arange(1, 20.5, None)\n verify_arange(1, 20, 3)\n verify_arange(20, 1, -1)\n verify_arange(20, 1, -1.5)\n\ndef test_repeat():\n verify_repeat((2,), 1, 0)\n verify_repeat((3, 2), 2, 0)\n verify_repeat((3, 2, 4), 3, 1)\n verify_repeat((1, 3, 2, 4), 4, -1)\n\ndef test_tile():\n verify_tile((3, 2), (2, 3))\n verify_tile((3, 2, 5), (2,))\n verify_tile((3, ), (2, 3, 3))\n\ndef test_layout_transform():\n in_shape = (1, 32, 8, 8)\n A = tvm.placeholder(shape=in_shape, dtype=\"float32\", name=\"A\")\n B = topi.layout_transform(A, \"NCHW\", \"NCHW16c\")\n\n input = np.random.uniform(size=in_shape).astype(A.dtype)\n output = np.transpose(input, axes=(0, 2, 3, 1))\n output = np.reshape(output, newshape=(1, 8, 8, 2, 16))\n output = np.transpose(output, axes=(0, 3, 1, 2, 4))\n\n def check_device(device):\n ctx = tvm.context(device, 0)\n if not ctx.exist:\n print(\"Skip because %s is not enabled\" % device)\n return\n tvm_input = tvm.nd.array(input, ctx)\n tvm_output = tvm.nd.empty(output.shape, ctx=ctx, dtype=B.dtype)\n print(\"Running on target: %s\" % device)\n with tvm.target.create(device):\n s = topi.generic.schedule_injective(B)\n f = tvm.build(s, [A, B], device, name=\"layout_transform\")\n f(tvm_input, tvm_output)\n tvm.testing.assert_allclose(tvm_output.asnumpy(), output)\n\n for backend in get_all_backend():\n check_device(backend)\n\n\ndef test_shape():\n in_shape = (8, 7, 13)\n dtype = \"int32\"\n A = tvm.placeholder(shape=in_shape, dtype=\"float32\", name=\"A\")\n B = topi.shape(A, dtype)\n\n input = np.random.uniform(size=in_shape).astype(A.dtype)\n output = np.asarray(in_shape).astype(dtype)\n\n def check_device(device):\n ctx = tvm.context(device, 0)\n if not ctx.exist:\n print(\"Skip because %s is not enabled\" % device)\n return\n tvm_input = tvm.nd.array(input, ctx)\n tvm_output = tvm.nd.empty(output.shape, ctx=ctx, dtype=dtype)\n print(\"Running on target: %s\" % device)\n with tvm.target.create(device):\n s = topi.generic.schedule_injective(B)\n f = tvm.build(s, [A, B], device, name=\"shape\")\n f(tvm_input, tvm_output)\n tvm.testing.assert_allclose(tvm_output.asnumpy(), output)\n\n for backend in get_all_backend():\n check_device(backend)\n\n\ndef test_sequence_mask():\n for in_shape in (5, 10), (3, 4, 5, 4):\n for axis in [0, 1]:\n for mask_value in [0.0, 1.0]:\n max_length = in_shape[axis]\n batch_size = in_shape[1 - axis]\n A = tvm.placeholder(shape=in_shape, dtype=\"float32\", name=\"A\")\n B = tvm.placeholder(shape=(batch_size,), dtype=\"int32\", name=\"B\")\n C = topi.sequence_mask(A, B, axis=axis, mask_value=mask_value)\n A_data = np.random.normal(0, 1, in_shape).astype(np.float32)\n B_data = np.random.randint(1, max_length, (batch_size,)).astype(np.int32)\n C_gt_data = topi.testing.sequence_mask(A_data, B_data, mask_value, axis)\n\n def check_device(device):\n ctx = tvm.context(device, 0)\n if not ctx.exist:\n print(\"Skip because %s is not enabled\" % device)\n return\n tvm_A = tvm.nd.array(A_data, ctx)\n tvm_B = tvm.nd.array(B_data, ctx)\n tvm_C = tvm.nd.empty(in_shape, ctx=ctx, dtype=\"float32\")\n print(\"Running on target: %s\" % device)\n with tvm.target.create(device):\n s = topi.generic.schedule_injective(C)\n f = tvm.build(s, [A, B, C], device, name=\"SequenceMask\")\n f(tvm_A, tvm_B, tvm_C)\n tvm.testing.assert_allclose(tvm_C.asnumpy(), C_gt_data)\n for backend in get_all_backend():\n check_device(backend)\n\ndef test_ndarray_size():\n in_shape = (5, 11, 7)\n dtype = \"int32\"\n A = tvm.placeholder(shape=in_shape, dtype=\"float32\", name=\"A\")\n B = topi.ndarray_size(A, dtype)\n\n input = np.random.uniform(size=in_shape).astype(A.dtype)\n output = np.asarray(np.size(input)).astype(dtype)\n\n def check_device(device):\n ctx = tvm.context(device, 0)\n if not ctx.exist:\n print(\"Skip because %s is not enabled\" % device)\n return\n tvm_input = tvm.nd.array(input, ctx=ctx)\n tvm_output = tvm.nd.empty((1,), ctx=ctx, dtype=B.dtype)\n print(\"Running on target: %s\" % device)\n with tvm.target.create(device):\n s = topi.generic.schedule_injective(B)\n f = tvm.build(s, [A, B], device, name=\"ndarray_size\")\n f(tvm_input, tvm_output)\n tvm.testing.assert_allclose(tvm_output.asnumpy(), output)\n\n for backend in get_all_backend():\n check_device(backend)\n\n\ndef test_where_fusion():\n \"\"\"integration test that where and zeros should be properly inlined\"\"\"\n def check_device(device):\n with tvm.target.create(device):\n ctx = tvm.context(device, 0)\n if not ctx.exist:\n print(\"Skip because %s is not enabled\" % device)\n return\n print(\"Running on target: %s\" % device)\n data = tvm.placeholder((2, 1, 2, 4), 'int8', 'data')\n w = tvm.placeholder((3, 1, 2, 2), 'int8', 'w')\n conv1 = topi.nn.conv2d(data, w, 1, 0, 1, out_dtype='int32')\n zeros = topi.full((2, 3, 1, 3), 'int32', tvm.const(0, dtype='int32'))\n gt = topi.greater_equal(conv1, zeros)\n one = topi.full((2, 3, 1, 3), 'int32', tvm.const(1, dtype='int32'))\n two = topi.full((2, 3, 1, 3), 'int32', tvm.const(2, dtype='int32'))\n where = topi.where(gt, one, two)\n add = topi.add(conv1, where)\n outs = [add]\n s = topi.generic.schedule_conv2d_nchw(outs)\n tvm.build(s, [data, w, add], target=backend)\n\n for backend in get_all_backend():\n check_device(backend)\n\n\nif __name__ == \"__main__\":\n # test_strided_slice()\n # test_concatenate()\n # test_stack()\n # test_transpose()\n test_feature_flatten()\n # test_flatten()\n # test_expand_dims()\n # test_reshape()\n # test_where()\n # test_squeeze()\n # test_split()\n # test_flip()\n # test_expand_like()\n # test_take()\n # test_gather_nd()\n # test_arange()\n # test_layout_transform()\n # test_repeat()\n # test_tile()\n # test_shape()\n # test_sequence_mask()\n # test_ndarray_size()\n # test_where_fusion()\n"
] | [
[
"numpy.take",
"numpy.asarray",
"numpy.size",
"numpy.stack",
"numpy.transpose",
"numpy.reshape",
"numpy.expand_dims",
"numpy.where",
"numpy.random.uniform",
"numpy.tile",
"numpy.zeros",
"numpy.repeat",
"numpy.arange",
"numpy.prod",
"numpy.array",
"numpy.empty",
"numpy.squeeze",
"numpy.random.randn",
"numpy.flip",
"numpy.random.normal",
"numpy.concatenate",
"numpy.random.randint",
"numpy.split"
]
] |
algchyhao/WNTR | [
"dd4db188a8641a4da16cf80a1557c908fa48c17d"
] | [
"wntr/scenario/earthquake.py"
] | [
"\"\"\"\nThe wntr.scenario.earthquake module includes methods to\ndefine an earthquake location, magnitude and depth, and\ncompute PGA, PGV, and repair rate.\n\"\"\"\nfrom __future__ import print_function\nimport wntr\nimport numpy as np\nimport pandas as pd\nfrom scipy.spatial import distance\n\nclass Earthquake(object):\n \"\"\"\n Earthquake scenario class.\n \"\"\"\n\n def __init__(self, epicenter, magnitude, depth):\n self.epicenter = epicenter\n \"\"\" Earthquake epicenter, (x,y) tuple in meters\"\"\"\n self.magnitude = magnitude\n \"\"\"Earthquake magnitude, Richter scale\"\"\"\n self.depth = depth\n \"\"\"Earthquake depth, m\"\"\"\n\n def distance_to_epicenter(self, wn, element_type=wntr.network.Node):\n \"\"\"\n Distance to the epicenter\n\n Parameters\n -----------\n wn : WaterNetworkModel\n\n element_type: optional (default = wntr.network.Node)\n\n Returns\n ---------\n A pandas Series with distance to epicenter (m)\n \"\"\"\n\n R = pd.Series()\n\n if element_type in [wntr.network.Link, wntr.network.Pipe, wntr.network.Pump, wntr.network.Valve]:\n # Compute pipe center position\n link_pos = {}\n for name, link in wn.links(element_type):\n start_point = link.start_node.coordinates\n end_point = link.end_node.coordinates\n link_pos[name] = ((end_point[0] + start_point[0])/2,\n (end_point[1] + start_point[1])/2)\n\n for name, link in wn.links(element_type):\n R[name] = distance.euclidean(self.epicenter, link_pos[name]) # m\n\n elif element_type in [wntr.network.Node, wntr.network.Junction, wntr.network.Tank, wntr.network.Reservoir]:\n for name, node in wn.nodes(element_type):\n R[name] = distance.euclidean(self.epicenter, node.coordinates) # m\n\n return R\n\n def pga_attenuation_model(self,R,method=None):\n \"\"\"\n Peak ground acceleration attenuation models\n\n Parameters\n -----------\n R : pd.Series\n Distance to epicenter (m)\n\n method : int (optional, default = None, average)\n 1 = Kawashima et al. (1984)\n 2 = Baag et al. (1998)\n 3 = Lee and Cho (2002)\n\n Returns\n --------\n A pandas Series with peak ground acceleration (g)\n \"\"\"\n R = R/1000 # convert m to km\n D = self.depth/1000 # convert m to km\n delta = np.sqrt(np.power(R,2) + np.power(D,2))\n\n if method == 1:\n # Kawashima et al. (1984)\n PGA = 403.8*np.power(10, 0.265*self.magnitude)*np.power(R+30, -1.218)\n elif method == 2:\n # Baag et al. (1998)\n PGA = np.exp(0.4 + 1.2*self.magnitude - 0.76*np.log(delta) - 0.0094*delta)\n elif method == 3:\n # Lee and Cho (2002)\n PGA = np.power(10, -1.83 + 0.386*self.magnitude - np.log10(R) - 0.0015*R)\n else:\n # Average of the three methods\n PGA = ((403.8*np.power(10, 0.265*self.magnitude)*np.power(R+30, -1.218)) + \\\n np.exp(0.4 + 1.2*self.magnitude - 0.76*np.log(delta) - 0.0094*delta) + \\\n np.power(10, -1.83 + 0.386*self.magnitude - np.log10(R) - 0.0015*R))/3\n\n PGA = PGA/100 # convert cm/s2 to m/s2\n\n PGA = PGA/9.81 # convert m/s2 to g\n\n return PGA\n\n def pgv_attenuation_model(self, R, method=None):\n \"\"\"\n Peak ground velocity attenuation models\n\n Parameters\n -----------\n R : pd.Series\n Distance to epicenter (m)\n\n method : int (optional, default = None, average)\n 1 = Yu and Jin (2008) - Rock\n 2 = Yu and Jin (2008) - Soil\n\n Returns\n --------\n A pandas Series with peak ground velocity (m/s)\n \"\"\"\n R = R/1000 # convert m to km\n\n if method == 1:\n # Yu and Jin (2008) - Rock\n PGV = np.power(10, -0.848 + 0.775*self.magnitude + -1.834*np.log10(R+17))\n elif method == 2:\n # Yu and Jin (2008) - Soil\n PGV = np.power(10, -0.285 + 0.711*self.magnitude + -1.851*np.log10(R+17))\n else:\n # Average\n PGV = (np.power(10, -0.848 + 0.775*self.magnitude + -1.834*np.log10(R+17)) + \\\n np.power(10, -0.285 + 0.711*self.magnitude + -1.851*np.log10(R+17)))/2\n\n PGV = PGV/100 # convert cm/s to m/s\n\n return PGV\n\n def correction_factor(self, pipe_characteristics, diameter_weight=None, material_weight=None,\n topography_weight=None, liquifaction_weight=None):\n \"\"\"\n Correction factor, maps pipe characteristics to weights\n \n Parameters\n -----------\n pipe_characteristics : pd.DataFrame\n Pipe characteristics which includes diameter, material, topography, and liquifaction\n \n diameter_weight, material_weight, topography_weight, liquifaction_weight: dict\n Weights, defaults based on Isoyama et al., 2000\n \n Returns\n --------\n A pandas Series with the correction factor\n \"\"\"\n\n # Make sure the values are strings\n pipe_characteristics = pd.DataFrame(data = pipe_characteristics.values, columns =pipe_characteristics.columns, index = pipe_characteristics.index.astype('str'))\n\n if diameter_weight is None:\n diameter_weight = {'Very small': 1.6, 'Small': 1.0, 'Medium': 0.8, 'Large': 0.5}\n\n if material_weight is None:\n material_weight = {'ACP': 1.2, 'PV': 1.0, 'PVC': 1.0, 'CIP': 1.0,\n 'PE': 0.8, 'HI-3P': 0.8, 'SP': 0.3, 'DCIP': 0.3}\n\n if topography_weight is None:\n topography_weight = {'Narrow valley': 3.2, 'Terrace': 1.5,\n 'Disturbed hill': 1.1, 'Alluvial': 1.0, 'Stiff alluvial': 0.4}\n\n if liquifaction_weight is None:\n liquifaction_weight = {'Total': 2.4, 'Partial': 2.0, 'None': 1.0}\n\n C0 = pipe_characteristics['Diameter'].map(diameter_weight)\n C1 = pipe_characteristics['Material'].map(material_weight)\n C2 = pipe_characteristics['Topography'].map(topography_weight)\n C3 = pipe_characteristics['Liquifaction'].map(liquifaction_weight)\n C = C0*C1*C2*C3\n\n return C\n\n def repair_rate_model(self, PGV, C=1, method=1):\n \"\"\"\n Calculate repair rate\n\n Parameters\n ------------\n PGV : pd.Series\n Peak ground velocity (m/s)\n\n K : pd.Series\n Correction factor\n\n method : int (default = 1)\n 1 = Linear\n 2 = Power\n\n Returns\n -------\n A pandas Series with repair rate (number of repairs per m)\n \"\"\"\n PGV = (100*PGV)/2.54 # in/s\n\n if method == 1:\n # linear model\n RR = C*0.00187*PGV\n elif method == 2:\n # Power model\n RR = C*0.00108*np.power(PGV, 1.173)\n else:\n print(\"invalid method\")\n\n RR = RR*(3.28/1000) # convert 1/1000ft to 1/m\n\n return RR\n\n def DTGR(self,M,M_min,M_max,b):\n \"\"\"\n Returns the the Doubly Truncated Gutenberg Richter cumulative probability\n for the specified magnitude, magnitude range, and coefficient.\n \"\"\"\n B = b*np.log(10)\n P = 1 - (np.exp(-B*M) - np.exp(-B*M_max))/(np.exp(-B*M_min) - np.exp(-B*M_max))\n\n return P\n\n def DTGR_inv(self, P,M_min,M_max,b):\n \"\"\"\n Returns the inverse of the Doubly Truncated Gutenberg Richter distribution\n for the specified probability, magnitude range, and coefficient.\n \"\"\"\n B = b*np.log(10)\n M = np.log(np.exp(-B*M_min) - P*(np.exp(-B*M_min)-np.exp(-B*M_max)))/(-B)\n\n return M\n"
] | [
[
"pandas.Series",
"scipy.spatial.distance.euclidean",
"numpy.exp",
"numpy.log",
"numpy.power",
"numpy.log10"
]
] |
reiserm/Xana | [
"056f2bf2da67ba0dade49bb4b56ea2afd42b36bd"
] | [
"Xana/SaxsAna/phicorr.py"
] | [
"import numpy as np\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy import fftpack as fp\n\n\ndef cross_correlation(q):\n ind = np.argmin(np.abs(q - 0.6))\n inten = I2d[:, ind]\n print(\"Found %d angles\" % len(inten))\n phi = chi.copy()\n\n N = len(inten)\n lags = np.arange(-N + 1, N)\n\n inten = inten - inten.mean()\n\n acf = np.correlate(inten, inten, mode=\"full\")\n acf /= N * inten.std() ** 2\n\n l = len(acf)\n x = np.linspace(-4 * np.pi, 4 * np.pi, l)\n print(N, \"Mean Intensity is: \" + str(mean_int_2))\n figure()\n plt.plot(lags, acf, \"-\")\n plt.grid()\n\n fourier = fp.fft(acf)\n xf = fp.fftfreq(l, d=1 / (2 * 360))\n xf = fp.fftshift(xf)\n fourier = fp.fftshift(fourier)\n fourier = 1.0 / l * np.absolute(fourier)\n # fourier = fourier[1:]\n # xf = xf[:l//2]\n\n plt.figure()\n plt.plot(xf, fourier)\n plt.grid()\n # # plt.savefig(savdir + 'phi_corr_long_fourier.png', format='png',dpi=400)\n\n # plt.show()\n"
] | [
[
"matplotlib.pyplot.grid",
"scipy.fftpack.fft",
"matplotlib.pyplot.figure",
"numpy.abs",
"numpy.correlate",
"numpy.arange",
"scipy.fftpack.fftfreq",
"scipy.fftpack.fftshift",
"numpy.absolute",
"matplotlib.pyplot.plot",
"numpy.linspace"
]
] |
KougatCylinder5/CAPT | [
"3a4ad2ef73529ae0ce85937070aa15ffc9a3ac8a"
] | [
"old/MoCap V0.1.0.py"
] | [
"#Cory Mavis\n\nimport cv2\nimport numpy\nimport sys\nimport subprocess\nimport os\nimport statistics\ncv2.namedWindow(\"LiveFeed\")\n\ndef callback (event,x,y,flags,params):\n global blueMark #update the position of the blue point\n global greenMark #update the position of the green point\n global redMark #update the position of the red point\n global state #update global value\n global maxred\n global minred\n global maxblue\n global minblue\n global maxgreen\n global mingreen\n global gx,gy\n global hsv\n if(params[0] == 1 and flags == 1):\n \n if(params[1] == 0):\n blueMark = state[y,x]\n print(blueMark)\n \n elif(params[1] == 1):\n greenMark = state[y,x]\n print(greenMark)\n \n elif(params[1] == 2):\n redMark = state[y,x]\n print(redMark)\n \n state[1] = params[1] + 1\n if(state[1] == 3):\n state = numpy.array([0,0,state[3]])\n gx = x\n gy = y\n print(hsv[y,x])\n \nstate = numpy.array([0,0])\ncv2.setMouseCallback(\"LiveFeed\",callback,state)\n\nvid = cv2.VideoCapture(0)\nvid.set(cv2.CAP_PROP_AUTO_EXPOSURE,0.25)\nvid.set(cv2.CAP_PROP_EXPOSURE, -5.0)\n \ndef recalibrate(value):\n global state\n if(value == 1):\n state[0] = 1\n print(\"Choose New Points for color calibration in this order:\")\n print(\"Blue, Green, Red\")\n state = numpy.array(state[0],state[1],hsv)\n cv2.setTrackbarPos(\"Recalibrate\",\"LiveFeed\",0)\n\ncv2.createTrackbar(\"Recalibrate\",\"LiveFeed\",0,1,recalibrate)\n\nmaxred = (8,255,255)\nminred = (2,130,55)\nmaxgreen = (90,255,255)\nmingreen = (50,100,20)\nmaxblue = (120,255,255)\nminblue = (100,50,0)\n\nwhile(cv2.waitKey(1) != 27):\n ret,frame = vid.read()\n if(not ret):\n print(\"Broke\")\n break\n ogFrame = frame.copy()\n frame = cv2.blur(frame, (20,20),cv2.BORDER_DEFAULT)\n hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)\n cv2.imshow(\"blur\",frame)\n \n redParts = cv2.inRange(hsv,minred,maxred)\n greenParts = cv2.inRange(hsv,mingreen,maxgreen)\n blueParts = cv2.inRange(hsv,minblue,maxblue)\n \n kernel = numpy.ones((10,10),numpy.uint8)\n \n redParts = cv2.morphologyEx(redParts, cv2.MORPH_OPEN, kernel)\n redParts = cv2.morphologyEx(redParts, cv2.MORPH_CLOSE, kernel)\n \n greenParts = cv2.morphologyEx(greenParts, cv2.MORPH_OPEN, kernel)\n greenParts = cv2.morphologyEx(greenParts, cv2.MORPH_CLOSE, kernel)\n \n blueParts = cv2.morphologyEx(blueParts, cv2.MORPH_OPEN, kernel)\n blueParts = cv2.morphologyEx(blueParts, cv2.MORPH_CLOSE, kernel)\n \n cv2.imshow(\"Angles Feed\",redParts)\n cv2.imshow(\"Green Parts\",greenParts)\n cv2.imshow(\"Blue Parts\",blueParts)\n \n M = cv2.moments(redParts)\n cXR = None\n if(M[\"m00\"] != 0):\n cXR = int(M[\"m10\"] / M[\"m00\"])\n cYR = int(M[\"m01\"] / M[\"m00\"])\n cv2.circle(ogFrame,(cXR, cYR),15,(0,0,255),-1)\n middle = hsv[cYR,cXR][1] + 30\n if(middle > 255):\n middle = 255\n #minred = [hsv[cYR,cXR][0] - 2,middle - 125,0]\n #maxred = [hsv[cYR,cXR][0] + 2,middle,255]\n \n \n M = cv2.moments(greenParts)\n cXG = None\n if(M[\"m00\"] != 0):\n cXG = int(M[\"m10\"] / M[\"m00\"])\n cYG = int(M[\"m01\"] / M[\"m00\"])\n cv2.circle(ogFrame,(cXG, cYG),15,(0,255,0),-1)\n print(hsv[cYG,cXG])\n \n M = cv2.moments(blueParts)\n cXB = None\n if(M[\"m00\"] != 0):\n cXB = int(M[\"m10\"] / M[\"m00\"])\n cYB = int(M[\"m01\"] / M[\"m00\"])\n cv2.circle(ogFrame,(cXB, cYB),15,(255,0,0),-1)\n #print(cXB,cYB,hsv[cYB,cXB])\n complete = 0\n \n if(cXG != None and cXR != None): \n cv2.line(ogFrame,(cXG,cYG),(cXR,cYR),(255,255,255),10)\n complete = complete + 1\n \n if(cXG != None and cXB != None): \n cv2.line(ogFrame,(cXG,cYG),(cXB,cYB),(255,255,255),10)\n complete = complete + 1\n \n if(complete == 2):\n \n points = numpy.array([[cXR,cYR], [cXG,cYG], [cXB,cYB]])\n \n A = points[2] - points[0]\n B = points[1] - points[0]\n C = points[2] - points[1]\n\n angles = []\n \n for e1, e2 in ((A, B), (A, C), (B, -C)):\n num = numpy.dot(e1, e2)\n denom = numpy.linalg.norm(e1) * numpy.linalg.norm(e2)\n angles.append(numpy.arccos(num/denom) * 180 / numpy.pi)\n \n print((int(statistics.mean([cXR,cXG,cXB])),int(statistics.mean([cYR,cYG,cYB]))))\n cv2.putText(ogFrame,str(round(angles[2],0))[:-2] + \" degrees\",(int(statistics.mean([cXR,cXG,cXB])),int(statistics.mean([cYR,cYG,cYB]))),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,0),3)\n\n cv2.imshow(\"LiveFeed\",ogFrame)\n \ncv2.destroyAllWindows()\nvid.release()\n"
] | [
[
"numpy.ones",
"numpy.arccos",
"numpy.array",
"numpy.dot",
"numpy.linalg.norm"
]
] |
Code-Papers/MAIPO | [
"2e5b911c7009ac9ad09e7129c7ef0992f2690d04"
] | [
"happo/trainer/happo.py"
] | [
"import numpy as np\nimport random\nfrom numpy.core.fromnumeric import clip\nfrom numpy.lib.shape_base import vsplit\nimport tensorflow as tf\nfrom tensorflow.python.ops.gen_linalg_ops import self_adjoint_eig_eager_fallback\nimport common.tf_util as U\n\nfrom common.distributions import make_pdtype\nimport tensorflow.contrib.layers as layers\nfrom tensorflow.python.ops.gen_math_ops import log, tanh\n\ndef Agent_train(obs_shape_n, act_space_n, p_index, p_func, v_func, optimizer, clip_range=0.2, grad_norm_clipping=0.5, num_units=64, scope=\"trainer\", reuse=None):\n '''\n List: obs_shape_n, -the obsevation shape of each agent e.g. obs_shape_n[i] = 1, it shows the obseration shape of agent i is 1\n List: act_space_n, -the action space of each agent, including the action shape, e.g. act_space_n[i] = [action1_limit, action2_limit, ...], where action1_limit = [max, min]\n Int: p_index, -the ID of current agent\n Fun: p_func, v_func, -the funcion of policy and value networks \n '''\n with tf.variable_scope(scope, reuse=reuse):\n # creat distributions\n act_pdtype = make_pdtype(act_space_n[p_index])\n\n # set up placeholders\n A = act_pdtype.sample_placeholder([None], name=\"action\"+str(p_index))\n obs_ph_n = [U.BatchInput(obs_shape_n[i], name=\"observation\"+str(i)).get() for i in range(len(obs_shape_n))]\n X = U.BatchInput(obs_shape_n[p_index], name=\"Agentobservation\"+str(p_index)).get()\n ADV = tf.placeholder(tf.float32, [None], name=\"advantage\"+str(p_index))\n R = tf.placeholder(tf.float32, [None], name=\"return\"+str(p_index))\n OLDLOGPAC = tf.placeholder(tf.float32, [None], name=\"oldlogpac\"+str(p_index))\n OLDVPRED = tf.placeholder(tf.float32, [None], name=\"oldvalue\"+str(p_index))\n\n # policy (actor): from X to action distribution\n p = p_func(X, int(act_pdtype.param_shape()[0]), scope=\"p_func\", num_units=num_units)\n p_func_vars = U.scope_vars(U.absolute_scope_name(\"p_func\"))\n\n # wrap parameters in distribution\n act_pd = act_pdtype.pdfromflat(p)\n\n act_sample = act_pd.sample()\n\n # log(probability) of A under current action distribution\n log_pac = act_pd.logp(A)\n\n # calculate ratio (pi(A|S) current policy / pi_old(A|S) old policy)\n ratio = tf.exp(log_pac - OLDLOGPAC)\n\n # defining Loss = - J is equivalent to max J\n pg_losses = -ADV * ratio\n\n pg_losses2 = -ADV * tf.clip_by_value(ratio, 1.0 - clip_range, 1.0 + clip_range) \n \n # final PG loss\n pg_loss = tf.reduce_mean(tf.maximum(pg_losses, pg_losses2))\n # pg_loss = tf.reduce_mean(pg_losses2)\n p_optimize_expr = U.minimize_and_clip(optimizer, pg_loss, p_func_vars, grad_norm_clipping)\n\n # Create callable functions\n p_train = U.function(inputs=[X] + [A] + [OLDLOGPAC] + [ADV], outputs=pg_loss, updates=[p_optimize_expr])\n log_px = U.function(inputs=[X] + [A], outputs=log_pac)\n act = U.function(inputs=[X], outputs=act_sample)\n\n # value (critic): from S to V(S), S is the state of environment\n S = tf.concat(obs_ph_n, 1)\n vpred = v_func(S, 1, scope=\"v_func\", num_units=num_units)[:,0]\n v_func_vars = U.scope_vars(U.absolute_scope_name(\"v_func\"))\n vpredclipped = OLDVPRED + tf.clip_by_value(vpred - OLDVPRED, - clip_range, clip_range)\n # Unclipped value\n vf_losses1 = tf.square(vpred - R)\n # Clipped value\n vf_losses2 = tf.square(vpredclipped - R)\n\n vf_loss = tf.reduce_mean(tf.maximum(vf_losses1, vf_losses2))\n # vf_loss = tf.reduce_mean(vf_losses1)\n v_optimize_expr = U.minimize_and_clip(optimizer, vf_loss, v_func_vars, grad_norm_clipping)\n\n v_train = U.function(inputs=obs_ph_n + [OLDVPRED] + [R], outputs=vf_loss, updates=[v_optimize_expr])\n vs = U.function(inputs=obs_ph_n, outputs=vpred)\n\n return act, p_train, log_px, v_train, vs\n\ndef Agents_train(obs_shape_n, v_func, optimizer, clip_range=0.2, grad_norm_clipping=0.5, num_units=64, scope=\"trainer\", reuse=None):\n with tf.variable_scope(scope, reuse=reuse):\n R = tf.placeholder(tf.float32, [None])\n OLDVPRED = tf.placeholder(tf.float32, [None])\n obs_ph_n = []\n for i in range(len(obs_shape_n)):\n obs_ph_n.append(U.BatchInput(obs_shape_n[i], name=\"observation\"+str(i)).get())\n\n v_input = tf.concat(obs_ph_n, 1)\n vpred = v_func(v_input, 1, scope=\"v_func\", num_units=num_units)[:, 0]\n v_func_vars = U.scope_vars(U.absolute_scope_name(\"v_func\"))\n vpredclipped = OLDVPRED + tf.clip_by_value(vpred - OLDVPRED, - clip_range, clip_range)\n\n # Unclipped value\n vf_losses1 = tf.square(vpred - R)\n # Clipped value\n vf_losses2 = tf.square(vpredclipped - R)\n\n vf_loss = tf.reduce_mean(tf.maximum(vf_losses1, vf_losses2))\n v_optimize_expr = U.minimize_and_clip(optimizer, vf_loss, v_func_vars, grad_norm_clipping)\n\n v_train = U.function(inputs=obs_ph_n + [OLDVPRED] + [R], outputs=vf_loss, updates=[v_optimize_expr])\n vs = U.function(inputs=obs_ph_n, outputs=vpred)\n\n return v_train, vs\n\nclass HAPPOAgentTrainer(object):\n def __init__(self, name, model, obs_shape_n, act_space_n, agent_index, clip_range, args):\n self.args = args\n self.actor, self.p_train, self.log_px, self.v_train, self.vs = Agent_train(\n scope=name, \n obs_shape_n=obs_shape_n, \n act_space_n=act_space_n, \n p_index=agent_index, \n p_func=model, \n v_func=model, \n optimizer=tf.train.AdamOptimizer(learning_rate=args.lr),\n clip_range=clip_range, \n grad_norm_clipping=10, \n num_units=args.num_units) \n self.agent_index = agent_index\n # optimizer=tf.train.AdamOptimizer(learning_rate=args.lr),\n\n def log_p(self, obs, act):\n return self.log_px(*([obs] + [act]))\n\n def value_s(self, state):\n return self.vs(*(state))\n \n def action(self, obs):\n return self.actor(*([obs]))\n \n def step(self, state):\n act = self.action(state[self.agent_index])\n logp = self.log_p(state[self.agent_index], act)\n val = self.value_s(state)\n return act, logp, val\n \n def experience(self, raw_samples):\n\n self.obs_t, self.obs_tp1, self.act, self.rew, self.ret, self.val_st, self.val_stp1, self.logp = [], [], [], [], [], [], [], []\n\n # deliver the samples\n self.obs_t = raw_samples[0]\n self.act = raw_samples[1]\n self.logp = raw_samples[2]\n\n def update(self, num_batch, M_adv):\n\n p_loss, v_loss = [], []\n\n # compute the number of batch used to train\n num_samples = len(self.logp)\n\n # divide samples into n batches to train\n for start in range(0, num_samples, num_batch):\n end = start + num_batch\n if (end <= num_samples):\n obs = self.obs_t[start:end]\n act = self.act[start:end]\n logp = self.logp[start:end]\n adv = M_adv[start:end]\n p_loss.append(self.p_train(*([obs] + [act] + [logp] + [adv])))\n else:\n print(\"ERROR: Index exceeds the number of training samples\")\n new_logp = self.log_p(self.obs_t, self.act) \n ratio_log = np.array(new_logp) - np.array(self.logp)\n ratio = np.exp(np.minimum(ratio_log, 1))\n M_adv = ratio * np.array(M_adv)\n M_adv = M_adv.tolist()\n return p_loss, M_adv\n \nclass HAPPOAgentsTrainer(object):\n def __init__(self, name, model, obs_shape_n, clip_range, args):\n self.args = args\n self.v_train, self.vs = Agents_train(\n scope=name, \n obs_shape_n=obs_shape_n, \n v_func=model, \n optimizer=tf.train.AdamOptimizer(learning_rate=args.lr), \n clip_range=clip_range,\n grad_norm_clipping=10,\n num_units=args.num_units)\n \n def value_s(self, obs):\n return self.vs(*(obs))\n \n def update(self, num_batch, state, val_st, ret):\n\n v_loss = []\n\n # compute the number of batch used to train\n num_samples = len(ret)\n\n # divide samples into n batches to train\n for start in range(0, num_samples, num_batch):\n end = start + num_batch\n if (end <= num_samples):\n obs_t = [state[i][start:end] for i in range(len(state))]\n val = val_st[start:end]\n ret = ret[start:end]\n v_loss.append(self.v_train(*(obs_t + [val] + [ret])))\n\n return v_loss"
] | [
[
"tensorflow.placeholder",
"tensorflow.train.AdamOptimizer",
"tensorflow.variable_scope",
"tensorflow.exp",
"tensorflow.square",
"tensorflow.concat",
"tensorflow.clip_by_value",
"numpy.array",
"tensorflow.maximum",
"numpy.minimum"
]
] |
holyYodu/mmpose | [
"c10225e61da2700b3cd309a6a6234c6280248a0b"
] | [
"tools/pytorch2onnx.py"
] | [
"import argparse\n\nimport mmcv\nimport numpy as np\nimport torch\nfrom mmcv.runner import load_checkpoint\n\nfrom mmpose.models import build_posenet\n\ntry:\n import onnx\n import onnxruntime as rt\nexcept ImportError as e:\n raise ImportError(f'Please install onnx and onnxruntime first. {e}')\n\ntry:\n from mmcv.onnx.symbolic import register_extra_symbolics\nexcept ModuleNotFoundError:\n raise NotImplementedError('please update mmcv to version>=1.0.4')\n\n\ndef _convert_batchnorm(module):\n \"\"\"Convert the syncBNs into normal BN3ds.\"\"\"\n module_output = module\n if isinstance(module, torch.nn.SyncBatchNorm):\n module_output = torch.nn.BatchNorm3d(module.num_features, module.eps,\n module.momentum, module.affine,\n module.track_running_stats)\n if module.affine:\n module_output.weight.data = module.weight.data.clone().detach()\n module_output.bias.data = module.bias.data.clone().detach()\n # keep requires_grad unchanged\n module_output.weight.requires_grad = module.weight.requires_grad\n module_output.bias.requires_grad = module.bias.requires_grad\n module_output.running_mean = module.running_mean\n module_output.running_var = module.running_var\n module_output.num_batches_tracked = module.num_batches_tracked\n for name, child in module.named_children():\n module_output.add_module(name, _convert_batchnorm(child))\n del module\n return module_output\n\n\ndef pytorch2onnx(model,\n input_shape,\n opset_version=11,\n show=False,\n output_file='tmp.onnx',\n verify=False):\n \"\"\"Convert pytorch model to onnx model.\n\n Args:\n model (:obj:`nn.Module`): The pytorch model to be exported.\n input_shape (tuple[int]): The input tensor shape of the model.\n opset_version (int): Opset version of onnx used. Default: 11.\n show (bool): Determines whether to print the onnx model architecture.\n Default: False.\n output_file (str): Output onnx model name. Default: 'tmp.onnx'.\n verify (bool): Determines whether to verify the onnx model.\n Default: False.\n \"\"\"\n model.cpu().eval()\n\n one_img = torch.randn(input_shape)\n\n register_extra_symbolics(opset_version)\n torch.onnx.export(\n model,\n one_img,\n output_file,\n export_params=True,\n keep_initializers_as_inputs=True,\n verbose=show,\n opset_version=opset_version)\n\n print(f'Successfully exported ONNX model: {output_file}')\n if verify:\n # check by onnx\n onnx_model = onnx.load(output_file)\n onnx.checker.check_model(onnx_model)\n\n # check the numerical value\n # get pytorch output\n pytorch_result = model(one_img).detach().numpy()\n\n # get onnx output\n input_all = [node.name for node in onnx_model.graph.input]\n input_initializer = [\n node.name for node in onnx_model.graph.initializer\n ]\n net_feed_input = list(set(input_all) - set(input_initializer))\n assert len(net_feed_input) == 1\n sess = rt.InferenceSession(output_file)\n onnx_result = sess.run(\n None, {net_feed_input[0]: one_img.detach().numpy()})[0]\n # only compare part of results\n assert np.allclose(\n pytorch_result, onnx_result,\n atol=1.e-5), 'The outputs are different between Pytorch and ONNX'\n print('The numerical values are same between Pytorch and ONNX')\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\n description='Convert MMPose models to ONNX')\n parser.add_argument('config', help='test config file path')\n parser.add_argument('checkpoint', help='checkpoint file')\n parser.add_argument('--show', action='store_true', help='show onnx graph')\n parser.add_argument('--output-file', type=str, default='tmp.onnx')\n parser.add_argument('--opset-version', type=int, default=11)\n parser.add_argument(\n '--verify',\n action='store_true',\n help='verify the onnx model output against pytorch output')\n parser.add_argument(\n '--shape',\n type=int,\n nargs='+',\n default=[1, 3, 256, 192],\n help='input size')\n args = parser.parse_args()\n return args\n\n\nif __name__ == '__main__':\n args = parse_args()\n\n assert args.opset_version == 11, 'MMPose only supports opset 11 now'\n\n cfg = mmcv.Config.fromfile(args.config)\n # build the model\n model = build_posenet(cfg.model)\n model = _convert_batchnorm(model)\n\n # onnx.export does not support kwargs\n if hasattr(model, 'forward_dummy'):\n model.forward = model.forward_dummy\n else:\n raise NotImplementedError(\n 'Please implement the forward method for exporting.')\n\n checkpoint = load_checkpoint(model, args.checkpoint, map_location='cpu')\n\n # conver model to onnx file\n pytorch2onnx(\n model,\n args.shape,\n opset_version=args.opset_version,\n show=args.show,\n output_file=args.output_file,\n verify=args.verify)\n"
] | [
[
"torch.randn",
"numpy.allclose",
"torch.onnx.export",
"torch.nn.BatchNorm3d"
]
] |
ludomitch/ml-agents | [
"481e2af4a96377c257a6aa5559d8b7230c432bad"
] | [
"ml-agents/mlagents/trainers/tests/test_policy.py"
] | [
"from mlagents.trainers.policy.tf_policy import TFPolicy\nfrom mlagents_envs.base_env import BatchedStepResult, AgentGroupSpec\nfrom mlagents.trainers.action_info import ActionInfo\nfrom unittest.mock import MagicMock\nimport numpy as np\n\n\ndef basic_mock_brain():\n mock_brain = MagicMock()\n mock_brain.vector_action_space_type = \"continuous\"\n mock_brain.vector_observation_space_size = 1\n mock_brain.vector_action_space_size = [1]\n return mock_brain\n\n\ndef basic_params():\n return {\"use_recurrent\": False, \"model_path\": \"my/path\"}\n\n\nclass FakePolicy(TFPolicy):\n def create_tf_graph(self):\n pass\n\n def get_trainable_variables(self):\n return []\n\n\ndef test_take_action_returns_empty_with_no_agents():\n test_seed = 3\n policy = FakePolicy(test_seed, basic_mock_brain(), basic_params())\n # Doesn't really matter what this is\n dummy_groupspec = AgentGroupSpec([(1,)], \"continuous\", 1)\n no_agent_step = BatchedStepResult.empty(dummy_groupspec)\n result = policy.get_action(no_agent_step)\n assert result == ActionInfo.empty()\n\n\ndef test_take_action_returns_nones_on_missing_values():\n test_seed = 3\n policy = FakePolicy(test_seed, basic_mock_brain(), basic_params())\n policy.evaluate = MagicMock(return_value={})\n policy.save_memories = MagicMock()\n step_with_agents = BatchedStepResult(\n [],\n np.array([], dtype=np.float32),\n np.array([False], dtype=np.bool),\n np.array([], dtype=np.bool),\n np.array([0]),\n None,\n )\n result = policy.get_action(step_with_agents, worker_id=0)\n assert result == ActionInfo(None, None, {}, [0])\n\n\ndef test_take_action_returns_action_info_when_available():\n test_seed = 3\n policy = FakePolicy(test_seed, basic_mock_brain(), basic_params())\n policy_eval_out = {\n \"action\": np.array([1.0], dtype=np.float32),\n \"memory_out\": np.array([[2.5]], dtype=np.float32),\n \"value\": np.array([1.1], dtype=np.float32),\n }\n policy.evaluate = MagicMock(return_value=policy_eval_out)\n step_with_agents = BatchedStepResult(\n [],\n np.array([], dtype=np.float32),\n np.array([False], dtype=np.bool),\n np.array([], dtype=np.bool),\n np.array([0]),\n None,\n )\n result = policy.get_action(step_with_agents)\n expected = ActionInfo(\n policy_eval_out[\"action\"], policy_eval_out[\"value\"], policy_eval_out, [0]\n )\n assert result == expected\n"
] | [
[
"numpy.array"
]
] |
rasimuvaikas/stanza | [
"21793519a531b0e9d7151e42d180d97785c9a5b8"
] | [
"stanza/models/lemmatizer.py"
] | [
"\"\"\"\nEntry point for training and evaluating a lemmatizer.\n\nThis lemmatizer combines a neural sequence-to-sequence architecture with an `edit` classifier \nand two dictionaries to produce robust lemmas from word forms.\nFor details please refer to paper: https://nlp.stanford.edu/pubs/qi2018universal.pdf.\n\"\"\"\n\nimport logging\nimport sys\nimport os\nimport shutil\nimport time\nfrom datetime import datetime\nimport argparse\nimport numpy as np\nimport random\nimport torch\nfrom torch import nn, optim\n\nfrom stanza.models.lemma.data import DataLoader\nfrom stanza.models.lemma.vocab import Vocab\nfrom stanza.models.lemma.trainer import Trainer\nfrom stanza.models.lemma import scorer, edit\nfrom stanza.models.common import utils\nimport stanza.models.common.seq2seq_constant as constant\nfrom stanza.models.common.doc import *\nfrom stanza.utils.conll import CoNLL\nfrom stanza.models import _training_logging\n\nlogger = logging.getLogger('stanza')\n\ndef parse_args(args=None):\n parser = argparse.ArgumentParser()\n parser.add_argument('--data_dir', type=str, default='data/lemma', help='Directory for all lemma data.')\n parser.add_argument('--train_file', type=str, default=None, help='Input file for data loader.')\n parser.add_argument('--eval_file', type=str, default=None, help='Input file for data loader.')\n parser.add_argument('--output_file', type=str, default=None, help='Output CoNLL-U file.')\n parser.add_argument('--gold_file', type=str, default=None, help='Output CoNLL-U file.')\n\n parser.add_argument('--mode', default='train', choices=['train', 'predict'])\n parser.add_argument('--lang', type=str, help='Language')\n\n parser.add_argument('--no_dict', dest='ensemble_dict', action='store_false', help='Do not ensemble dictionary with seq2seq. By default use ensemble.')\n parser.add_argument('--dict_only', action='store_true', help='Only train a dictionary-based lemmatizer.')\n\n parser.add_argument('--hidden_dim', type=int, default=200)\n parser.add_argument('--emb_dim', type=int, default=50)\n parser.add_argument('--num_layers', type=int, default=1)\n parser.add_argument('--emb_dropout', type=float, default=0.5)\n parser.add_argument('--dropout', type=float, default=0.5)\n parser.add_argument('--max_dec_len', type=int, default=50)\n parser.add_argument('--beam_size', type=int, default=1)\n\n parser.add_argument('--attn_type', default='soft', choices=['soft', 'mlp', 'linear', 'deep'], help='Attention type')\n parser.add_argument('--pos_dim', type=int, default=50)\n parser.add_argument('--pos_dropout', type=float, default=0.5)\n parser.add_argument('--no_edit', dest='edit', action='store_false', help='Do not use edit classifier in lemmatization. By default use an edit classifier.')\n parser.add_argument('--num_edit', type=int, default=len(edit.EDIT_TO_ID))\n parser.add_argument('--alpha', type=float, default=1.0)\n parser.add_argument('--no_pos', dest='pos', action='store_false', help='Do not use UPOS in lemmatization. By default UPOS is used.')\n\n parser.add_argument('--sample_train', type=float, default=1.0, help='Subsample training data.')\n parser.add_argument('--optim', type=str, default='adam', help='sgd, adagrad, adam or adamax.')\n parser.add_argument('--lr', type=float, default=1e-3, help='Learning rate')\n parser.add_argument('--lr_decay', type=float, default=0.9)\n parser.add_argument('--decay_epoch', type=int, default=30, help=\"Decay the lr starting from this epoch.\")\n parser.add_argument('--num_epoch', type=int, default=60)\n parser.add_argument('--batch_size', type=int, default=50)\n parser.add_argument('--max_grad_norm', type=float, default=5.0, help='Gradient clipping.')\n parser.add_argument('--log_step', type=int, default=20, help='Print log every k steps.')\n parser.add_argument('--model_dir', type=str, default='saved_models/lemma', help='Root dir for saving models.')\n\n parser.add_argument('--seed', type=int, default=1234)\n parser.add_argument('--cuda', type=bool, default=torch.cuda.is_available())\n parser.add_argument('--cpu', action='store_true', help='Ignore CUDA.')\n\n args = parser.parse_args(args=args)\n return args\n\ndef main(args=None):\n args = parse_args(args=args)\n\n torch.manual_seed(args.seed)\n np.random.seed(args.seed)\n random.seed(args.seed)\n if args.cpu:\n args.cuda = False\n elif args.cuda:\n torch.cuda.manual_seed(args.seed)\n\n args = vars(args)\n logger.info(\"Running lemmatizer in {} mode\".format(args['mode']))\n\n if args['mode'] == 'train':\n train(args)\n else:\n evaluate(args)\n\ndef train(args):\n # load data\n logger.info(\"[Loading data with batch size {}...]\".format(args['batch_size']))\n train_doc = Document(CoNLL.conll2dict(input_file=args['train_file']))\n train_batch = DataLoader(train_doc, args['batch_size'], args, evaluation=False)\n vocab = train_batch.vocab\n args['vocab_size'] = vocab['char'].size\n args['pos_vocab_size'] = vocab['pos'].size\n dev_doc = Document(CoNLL.conll2dict(input_file=args['eval_file']))\n dev_batch = DataLoader(dev_doc, args['batch_size'], args, vocab=vocab, evaluation=True)\n\n utils.ensure_dir(args['model_dir'])\n model_file = '{}/{}_lemmatizer.pt'.format(args['model_dir'], args['lang'])\n\n # pred and gold path\n system_pred_file = args['output_file']\n gold_file = args['gold_file']\n\n utils.print_config(args)\n\n # skip training if the language does not have training or dev data\n if len(train_batch) == 0 or len(dev_batch) == 0:\n logger.warning(\"[Skip training because no training data available...]\")\n return\n\n # start training\n # train a dictionary-based lemmatizer\n trainer = Trainer(args=args, vocab=vocab, use_cuda=args['cuda'])\n logger.info(\"[Training dictionary-based lemmatizer...]\")\n trainer.train_dict(train_batch.doc.get([TEXT, UPOS, LEMMA]))\n logger.info(\"Evaluating on dev set...\")\n dev_preds = trainer.predict_dict(dev_batch.doc.get([TEXT, UPOS]))\n dev_batch.doc.set([LEMMA], dev_preds)\n CoNLL.dict2conll(dev_batch.doc.to_dict(), system_pred_file)\n _, _, dev_f = scorer.score(system_pred_file, gold_file)\n logger.info(\"Dev F1 = {:.2f}\".format(dev_f * 100))\n\n if args.get('dict_only', False):\n # save dictionaries\n trainer.save(model_file)\n else:\n # train a seq2seq model\n logger.info(\"[Training seq2seq-based lemmatizer...]\")\n global_step = 0\n max_steps = len(train_batch) * args['num_epoch']\n dev_score_history = []\n best_dev_preds = []\n current_lr = args['lr']\n global_start_time = time.time()\n format_str = '{}: step {}/{} (epoch {}/{}), loss = {:.6f} ({:.3f} sec/batch), lr: {:.6f}'\n\n # start training\n for epoch in range(1, args['num_epoch']+1):\n train_loss = 0\n for i, batch in enumerate(train_batch):\n start_time = time.time()\n global_step += 1\n loss = trainer.update(batch, eval=False) # update step\n train_loss += loss\n if global_step % args['log_step'] == 0:\n duration = time.time() - start_time\n logger.info(format_str.format(datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"), global_step,\n max_steps, epoch, args['num_epoch'], loss, duration, current_lr))\n\n # eval on dev\n logger.info(\"Evaluating on dev set...\")\n dev_preds = []\n dev_edits = []\n for i, batch in enumerate(dev_batch):\n preds, edits = trainer.predict(batch, args['beam_size'])\n dev_preds += preds\n if edits is not None:\n dev_edits += edits\n dev_preds = trainer.postprocess(dev_batch.doc.get([TEXT]), dev_preds, edits=dev_edits)\n\n # try ensembling with dict if necessary\n if args.get('ensemble_dict', False):\n logger.info(\"[Ensembling dict with seq2seq model...]\")\n dev_preds = trainer.ensemble(dev_batch.doc.get([TEXT, UPOS]), dev_preds)\n dev_batch.doc.set([LEMMA], dev_preds)\n CoNLL.dict2conll(dev_batch.doc.to_dict(), system_pred_file)\n _, _, dev_score = scorer.score(system_pred_file, gold_file)\n\n train_loss = train_loss / train_batch.num_examples * args['batch_size'] # avg loss per batch\n logger.info(\"epoch {}: train_loss = {:.6f}, dev_score = {:.4f}\".format(epoch, train_loss, dev_score))\n\n # save best model\n if epoch == 1 or dev_score > max(dev_score_history):\n trainer.save(model_file)\n logger.info(\"new best model saved.\")\n best_dev_preds = dev_preds\n\n # lr schedule\n if epoch > args['decay_epoch'] and dev_score <= dev_score_history[-1] and \\\n args['optim'] in ['sgd', 'adagrad']:\n current_lr *= args['lr_decay']\n trainer.update_lr(current_lr)\n\n dev_score_history += [dev_score]\n logger.info(\"\")\n\n logger.info(\"Training ended with {} epochs.\".format(epoch))\n\n best_f, best_epoch = max(dev_score_history)*100, np.argmax(dev_score_history)+1\n logger.info(\"Best dev F1 = {:.2f}, at epoch = {}\".format(best_f, best_epoch))\n\ndef evaluate(args):\n # file paths\n system_pred_file = args['output_file']\n gold_file = args['gold_file']\n model_file = '{}/{}_lemmatizer.pt'.format(args['model_dir'], args['lang'])\n\n # load model\n use_cuda = args['cuda'] and not args['cpu']\n trainer = Trainer(model_file=model_file, use_cuda=use_cuda)\n loaded_args, vocab = trainer.args, trainer.vocab\n\n for k in args:\n if k.endswith('_dir') or k.endswith('_file') or k in ['shorthand']:\n loaded_args[k] = args[k]\n\n # load data\n logger.info(\"Loading data with batch size {}...\".format(args['batch_size']))\n doc = Document(CoNLL.conll2dict(input_file=args['eval_file']))\n batch = DataLoader(doc, args['batch_size'], loaded_args, vocab=vocab, evaluation=True)\n\n # skip eval if dev data does not exist\n if len(batch) == 0:\n logger.warning(\"Skip evaluation because no dev data is available...\\nLemma score:\\n{} \".format(args['lang']))\n return\n\n dict_preds = trainer.predict_dict(batch.doc.get([TEXT, UPOS]))\n\n if loaded_args.get('dict_only', False):\n preds = dict_preds\n else:\n logger.info(\"Running the seq2seq model...\")\n preds = []\n edits = []\n for i, b in enumerate(batch):\n ps, es = trainer.predict(b, args['beam_size'])\n preds += ps\n if es is not None:\n edits += es\n preds = trainer.postprocess(batch.doc.get([TEXT]), preds, edits=edits)\n\n if loaded_args.get('ensemble_dict', False):\n logger.info(\"[Ensembling dict with seq2seq lemmatizer...]\")\n preds = trainer.ensemble(batch.doc.get([TEXT, UPOS]), preds)\n\n # write to file and score\n batch.doc.set([LEMMA], preds)\n CoNLL.dict2conll(batch.doc.to_dict(), system_pred_file)\n if gold_file is not None:\n _, _, score = scorer.score(system_pred_file, gold_file)\n\n logger.info(\"Finished evaluation\\nLemma score:\\n{} {:.2f}\".format(args['lang'], score*100))\n\nif __name__ == '__main__':\n main()\n"
] | [
[
"torch.cuda.manual_seed",
"torch.manual_seed",
"numpy.random.seed",
"numpy.argmax",
"torch.cuda.is_available"
]
] |
sherrardTr4129/RealSense-BNO055-Pose-Estimation | [
"ca48f11ae53549b2782a7848ee5091e1ce8d30ff"
] | [
"kinect_vision_target_cap/src/find_obj_xyz.py"
] | [
"#!/usr/bin/env python\n\n# Author: Trevor Sherrard\n# Course: Directed Research\n# Since: 02/06/2021\n# Description: This script extracts synced RGB and Depth frames from \n# the kinect and attempts to locate a given vision target.\n# if the vision target is located, the XYZ coordinates are\n# scaled and published.\n\nimport freenect\nimport cv2\nimport numpy as np\nimport rospy\nimport pyrealsense2 as rs\nfrom geometry_msgs.msg import PointStamped\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge\nfrom WindowedAverage import MovingWindowAverage\n\ncv2.namedWindow('Depth')\ncv2.namedWindow('Video')\n\n# define various global variables\npointPubTopic = \"/vision_target_xyz_point\"\nvisionTargetImage = \"/visionTargetImage\"\nlowerColorBound = (0, 187, 83)\nupperColorBound = (255, 255, 255)\nMIN_AREA = 100\nWINDOW_SIZE = 3\n\n# create CvBridge object for converting CV2 images to sensor_msgs/Image messages\nimgBridge = CvBridge()\n\n# create image publisher object\nimgPub = rospy.Publisher(visionTargetImage, Image, queue_size=1)\n\ndef getDepth():\n \"\"\"\n This function extracts a synced depth image from the kinect.\n params:\n None\n returns:\n depth (uint8 frame): The depth image\n \"\"\"\n return frame_convert2.pretty_depth_cv(freenect.sync_get_depth(format=freenect.DEPTH_REGISTERED)[0])\n\ndef getRGB():\n \"\"\"\n This function extracts a synced RGB image from the kinect.\n params:\n None\n returns:\n RGB (uint8 frame): The RGB image\n \"\"\"\n return frame_convert2.video_cv(freenect.sync_get_video()[0])\n\ndef threshColorImage(colorImg, lowerColorBound, upperColorBound):\n \"\"\"\n This function takes a HSV image and two HSV color tuples and\n returns a thresholded image. \n\n params:\n colorImg (int8 HSV image): the HSV image to be thresholded\n lowerColorBound (int,int,int): the lower color threshold bound\n upperColorBound (int,int,int): the upper color threshold bound\n returns:\n threshedImg (uint8 image): a thresholded binary image\n \"\"\"\n threshedImage = cv2.inRange(colorImg, lowerColorBound, upperColorBound)\n return threshedImage\n\ndef findMinEnclosingCircle(frame):\n \"\"\"\n This function finds a circle that encloses the largest contour\n in a given image that is over a given size of MIN_AREA. If a circle is found,\n a True status boolean is returned, along with the circle's center coordinates and\n radius.\n\n params:\n frame (uint8 image): the RGB image from the kinect to process\n returns:\n status, circle (boool, ((x,y), radius)): the status indicating if a circle was found\n and the detected circle center point and radius\n \"\"\"\n # blur image\n blurKernel = (11, 11)\n blurred = cv2.GaussianBlur(frame, blurKernel, 0)\n\n # convert to HSV\n hsvImage = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)\n\n # threshold\n thresh = threshColorImage(hsvImage, lowerColorBound, upperColorBound)\n\n # open image\n kernel = np.ones((5,5), np.uint8)\n erode = cv2.erode(thresh, kernel, iterations=2)\n openedImage = cv2.dilate(erode, kernel, iterations=2)\n\n # find edges\n edges = cv2.Canny(openedImage, 0, 255)\n\n # find image contours from edge image\n contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n goodContours = []\n for cont in contours:\n area = cv2.contourArea(cont)\n if(area > MIN_AREA):\n goodContours.append(cont)\n\n defaultCircle = ((0,0),0)\n if(len(goodContours) > 0):\n #find biggest contour\n maxC = max(goodContours, key=cv2.contourArea)\n\n # find enclosing circle of biggest contour\n ((cx, cy), radius) = cv2.minEnclosingCircle(maxC)\n defaultCircle = ((cx, cy), radius)\n return True, defaultCircle\n else:\n return False, defaultCircle\n\ndef circle_to_realworld(depthImg, circle, depth_intrin):\n \"\"\"\n This function takes a given depth image from the Intel RealSense camera\n and the center point of the detected circle, and de-projects it into real\n world points. \n\n params:\n depthImg (depth frame): The depth image from the Intel RealSense\n circle ((int x, int y), int radius): the center point and radius of the detected circle\n depth_intrin (depth intrinsics): Intrinsic paramters of the depth frame.\n returns:\n real_world_point (int): the real world point of the detected circle \n \"\"\"\n # construct ROI\n (x,y), radius = circle\n x=int(x)\n y=int(y)\n radius=int(radius)\n\n # get depth value of circle center\n depth = depthImg.get_distance(x, y)\n\n # perform deprojection\n real_world_point = rs.rs2_deproject_pixel_to_point(depth_intrin, [x, y], depth)\n\n return real_world_point\n\n\ndef main():\n # start node\n rospy.init_node(\"kinect_find_xyz\")\n rospy.loginfo(\"kinect_find_xyz node initialized\")\n\n # create Point32 publisher\n pointPub = rospy.Publisher(pointPubTopic, PointStamped, queue_size=1)\n\n # create moving average filters\n WINDOW_SIZE = 4\n moving_avg_x = MovingWindowAverage(WINDOW_SIZE)\n moving_avg_y = MovingWindowAverage(WINDOW_SIZE)\n moving_avg_z = MovingWindowAverage(WINDOW_SIZE)\n\n # Create a pipeline\n pipeline = rs.pipeline()\n\n # Create a config and configure the pipeline to stream\n # different resolutions of color and depth streams\n config = rs.config()\n\n # Get device product line for setting a supporting resolution\n pipeline_wrapper = rs.pipeline_wrapper(pipeline)\n pipeline_profile = config.resolve(pipeline_wrapper)\n device = pipeline_profile.get_device()\n device_product_line = str(device.get_info(rs.camera_info.product_line))\n\n # enable depth and color streams\n config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)\n config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)\n\n # Start streaming\n profile = pipeline.start(config)\n\n # Getting the depth sensor's depth scale (see rs-align example for explanation)\n depth_sensor = profile.get_device().first_depth_sensor()\n depth_scale = depth_sensor.get_depth_scale()\n\n # Create an align object\n # rs.align allows us to perform alignment of depth frames to others frames\n # The \"align_to\" is the stream type to which we plan to align depth frames.\n align_to = rs.stream.color\n align = rs.align(align_to)\n\n\n while (not rospy.is_shutdown()):\n # grab frames from intel RealSense\n frames = pipeline.wait_for_frames()\n \n # Align the depth frame to color frame\n aligned_frames = align.process(frames)\n\n # Get aligned frames\n aligned_depth_frame = aligned_frames.get_depth_frame() # aligned_depth_frame is a 640x480 depth image\n color_frame = aligned_frames.get_color_frame()\n\n # get depth frame intrinsics\n depth_intrin = aligned_depth_frame.profile.as_video_stream_profile().intrinsics\n\n # Validate that both frames are valid\n if not aligned_depth_frame or not color_frame:\n continue\n\n # convert to numpy arrays\n numpyRGB = np.asanyarray(color_frame.get_data())\n numpyDepth = np.asanyarray(aligned_depth_frame.get_data())\n\n # find min enclosing circle \n status, circle = findMinEnclosingCircle(numpyRGB)\n\n if(status):\n # draw circles if they are found\n (x,y), radius = circle\n cv2.circle(numpyRGB, (int(x), int(y)), int(radius), (0,255,0),2)\n\n # find depth of detected circle\n reading = circle_to_realworld(aligned_depth_frame, circle, depth_intrin)\n\n average_x = moving_avg_x.addAndProc(reading[0])\n average_y = moving_avg_y.addAndProc(reading[1])\n average_z = moving_avg_z.addAndProc(reading[2])\n\n # invert sign of y-point to align with standard cartesian\n # views\n average_y = -1*average_y\n\n # create PointStamped message and publish\n pointMessage = PointStamped()\n pointMessage.header.stamp = rospy.Time.now()\n pointMessage.point.x = average_x\n pointMessage.point.y = average_y\n pointMessage.point.z = average_z\n pointPub.publish(pointMessage)\n\n # publish color image\n imgMsg = imgBridge.cv2_to_imgmsg(numpyRGB, \"bgr8\")\n imgPub.publish(imgMsg)\n\n # display images\n depth_colormap = cv2.applyColorMap(cv2.convertScaleAbs(numpyDepth, alpha=0.03), cv2.COLORMAP_JET)\n cv2.imshow('Depth', depth_colormap)\n cv2.imshow('Video', numpyRGB)\n if(cv2.waitKey(1) & 0xFF == ord('q')):\n break\n\nif(__name__ == \"__main__\"):\n main()\n"
] | [
[
"numpy.ones"
]
] |
BXuan694/basemodel-pytorch | [
"a36c96904580be902e323db17eebbe2ea1f54176"
] | [
"resnet.py"
] | [
"'''ResNet in PyTorch.\n\nFor Pre-activation ResNet, see 'preact_resnet.py'.\n\nReference:\n[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun\n Deep Residual Learning for Image Recognition. arXiv:1512.03385\n'''\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\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 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n\n self.shortcut = nn.Sequential()\n if stride != 1 or in_planes != self.expansion*planes:\n self.shortcut = nn.Sequential(\n nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(self.expansion*planes)\n )\n\n def forward(self, x):\n out = F.relu(self.bn1(self.conv1(x)))\n out = self.bn2(self.conv2(out))\n out += self.shortcut(x)\n out = F.relu(out)\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, in_planes, planes, stride=1):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv3 = nn.Conv2d(planes, self.expansion*planes, kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(self.expansion*planes)\n\n self.shortcut = nn.Sequential()\n if stride != 1 or in_planes != self.expansion*planes:\n self.shortcut = nn.Sequential(\n nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(self.expansion*planes)\n )\n\n def forward(self, x):\n out = F.relu(self.bn1(self.conv1(x)))\n out = F.relu(self.bn2(self.conv2(out)))\n out = self.bn3(self.conv3(out))\n out += self.shortcut(x)\n out = F.relu(out)\n return out\n\n\nclass ResNet(nn.Module):\n def __init__(self, block, num_blocks, numClasses=257):\n super(ResNet, self).__init__()\n self.in_planes = 64\n\n self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)\n self.bn1 = nn.BatchNorm2d(64)\n self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)\n self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)\n self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)\n self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)\n self.linear = nn.Linear(512*block.expansion*4, numClasses)\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 return nn.Sequential(*layers)\n\n def forward(self, x):\n out = F.relu(self.bn1(self.conv1(x)))\n out = self.layer1(out)\n out = self.layer2(out)\n out = self.layer3(out)\n out = self.layer4(out)\n out = F.avg_pool2d(out, 4)\n out = out.view(out.size(0), -1)\n out = self.linear(out)\n return out\n\n\ndef ResNet18():\n return ResNet(BasicBlock, [2,2,2,2])\n\ndef ResNet34():\n return ResNet(BasicBlock, [3,4,6,3])\n\ndef ResNet50():\n return ResNet(Bottleneck, [3,4,6,3])\n\ndef ResNet101():\n return ResNet(Bottleneck, [3,4,23,3])\n\ndef ResNet152():\n return ResNet(Bottleneck, [3,8,36,3])"
] | [
[
"torch.nn.BatchNorm2d",
"torch.nn.Linear",
"torch.nn.functional.avg_pool2d",
"torch.nn.functional.relu",
"torch.nn.Conv2d",
"torch.nn.Sequential"
]
] |
charlesCXK/PixelSSL | [
"2e85e12c1db5b24206bfbbf2d7f6348ae82b2105"
] | [
"task/sseg/criterion.py"
] | [
"import time\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\n\nimport pixelssl\n\n\ndef add_parser_arguments(parser):\n pixelssl.criterion_template.add_parser_arguments(parser)\n\n\ndef deeplab_criterion():\n return DeepLabCriterion\n\n\nclass DeepLabCriterion(pixelssl.criterion_template.TaskCriterion):\n def __init__(self, args):\n super(DeepLabCriterion, self).__init__(args)\n self.cross_entropy = nn.CrossEntropyLoss(\n ignore_index=self.args.ignore_index, reduction='none')\n\n def forward(self, pred, gt, inp):\n # NOTE: input 'pred' is not activated!\n\n if len(pred) != 1 or len(gt) != 1 or len(inp) != 1:\n pixelssl.log_err('DeepLab criterion for semantic segmentation requires\\t=>\\t'\n 'len(pred) == 1 \\t len(gt) == 1 \\t len(inp) == 1\\n')\n\n pred, gt, inp = pred[0], gt[0], inp[0]\n n, c, h, w = pred.shape\n\n if len(gt.shape) == 4:\n gt = gt.view(n, h, w)\n \n loss = self.cross_entropy(pred, gt.long())\n return torch.mean(loss, dim=(1, 2))\n"
] | [
[
"torch.mean",
"torch.nn.CrossEntropyLoss"
]
] |
Balaras-Group/flowX | [
"29c1d6209abbfab553997b557794e4d7b06a09a8"
] | [
"flowx/io/_interface/_plot_vector.py"
] | [
"\"\"\"Module with I/O functions.\"\"\"\n\nimport numpy\nfrom matplotlib import pyplot\n\n\ndef plot_vector(gridx, gridy, ivar):\n \"\"\"Plot the vector for given x, y data.\n\n Arguments\n ---------\n gridx : Grid object\n Grid containing the data on x-face.\n gridy : Grid object\n Grid containing the data on y-face.\n ivar : string\n Name of the ivariable to plot.\n\n \"\"\"\n xmesh, ymesh = numpy.meshgrid(gridx.x, gridy.y)\n\n uface = gridx[ivar][0, 0, :, :]\n vface = gridy[ivar][0, 0, :, :]\n\n umesh = (uface[1:, :] + uface[:-1, :]) / 2\n vmesh = (vface[:, 1:] + vface[:, -1:]) / 2\n\n pyplot.rc(\"font\", family=\"serif\", size=16)\n pyplot.figure()\n pyplot.xlabel(\"x\")\n pyplot.ylabel(\"y\")\n pyplot.quiver(xmesh, ymesh, umesh, vmesh)\n pyplot.axis(\"scaled\")\n pyplot.xlim(gridx.xmin, gridx.xmax)\n pyplot.ylim(gridy.ymin, gridy.ymax)\n pyplot.show()\n"
] | [
[
"matplotlib.pyplot.quiver",
"matplotlib.pyplot.rc",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.ylim",
"numpy.meshgrid",
"matplotlib.pyplot.xlabel"
]
] |
iolloj/jax | [
"1b80feea6acf758fd9dc3e616e8efcb8db831ce9"
] | [
"benchmarks/api_benchmark.py"
] | [
"# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Microbenchmarks for JAX `api` functions.\"\"\"\nimport functools\nimport operator\n\nimport google_benchmark\nimport jax\nimport jax.numpy as jnp\nimport numpy as np\nfrom jax import lax\n\n\npartial = functools.partial\n\ndef required_devices(num_devices_required):\n \"\"\"Helper to skip benchmarks that require more devices.\"\"\"\n def helper1(f):\n @functools.wraps(f)\n def helper2(state):\n if jax.device_count() < num_devices_required:\n state.skip_with_error(f\"requires {num_devices_required} devices\")\n return\n return f(state)\n return helper2\n return helper1\n\n\n@google_benchmark.register\ndef eager_unary_dispatch(state):\n a = jax.device_put(1)\n lax.neg(a)\n while state:\n lax.neg(a)\n\n\n@google_benchmark.register\ndef eager_unary(state):\n a = jax.device_put(1)\n lax.neg(a).block_until_ready()\n while state:\n lax.neg(a).block_until_ready()\n\n\n@google_benchmark.register\ndef eager_binary_dispatch(state):\n a = jax.device_put(1)\n b = jax.device_put(2)\n lax.add(a, b)\n while state:\n lax.add(a, b)\n\n\n@google_benchmark.register\ndef eager_binary(state):\n a = jax.device_put(1)\n b = jax.device_put(2)\n lax.add(a, b).block_until_ready()\n while state:\n lax.add(a, b).block_until_ready()\n\n\n@google_benchmark.register\ndef jit_trivial_dispatch(state):\n \"\"\"Benchmarks only the duration for jitted_f to return the future.\"\"\"\n f = jax.jit(swap)\n a, b = f(1, 2)\n x = f(a, b)\n while state:\n x = f(a, b)\n x[0].block_until_ready()\n\n\n@google_benchmark.register\ndef jit_trivial(state):\n f = jax.jit(swap)\n a, b = f(1, 2)\n f(a, b)\n\n while state:\n c, d = f(a, b)\n c.block_until_ready()\n d.block_until_ready()\n\n\n@google_benchmark.register\ndef jit_simple_dispatch(state):\n a = jax.device_put(1)\n b = jax.device_put(2)\n f = jax.jit(operator.add)\n f(a, b)\n\n while state:\n f(a, b)\n\n\n@google_benchmark.register\ndef jit_simple(state):\n a = jax.device_put(1)\n b = jax.device_put(2)\n f = jax.jit(operator.add)\n f(a, b)\n\n while state:\n f(a, b).block_until_ready()\n\n\ndef jit_simple_many_args_dispatch(n, state):\n args = [jax.device_put(i) for i in range(n)]\n f = jax.jit(lambda xs: functools.reduce(operator.add, xs))\n x = f(args)\n x.block_until_ready()\n\n while state:\n x = f(args)\n x.block_until_ready()\n\ndef jit_simple_many_args(n, state):\n args = [jax.device_put(i) for i in range(n)]\n f = jax.jit(lambda xs: functools.reduce(operator.add, xs))\n f(args).block_until_ready()\n\n while state:\n f(args).block_until_ready()\n\ndef jit_simple_pruned_args_dispatch(n, state):\n args = [jax.device_put(i) for i in range(n)]\n f = jax.jit(lambda *xs: xs[0] + 1)\n x = f(*args)\n x.block_until_ready()\n\n while state:\n x = f(*args)\n x.block_until_ready()\n\n\ndef jit_simple_pruned_args(n, state):\n args = [jax.device_put(i) for i in range(n)]\n f = jax.jit(lambda *xs: xs[0] + 1)\n x = f(*args)\n x.block_until_ready()\n\n while state:\n f(*args).block_until_ready()\n\nbenchmarks = []\nfor n in [10, 100, 1000, 2000]:\n benchmarks += [\n google_benchmark.register(partial(jit_simple_many_args_dispatch, n),\n name=f\"jit_simple_many_args_dispatch_{n}\"),\n google_benchmark.register(partial(jit_simple_many_args, n),\n name=f\"jit_simple_many_args_{n}\"),\n google_benchmark.register(partial(jit_simple_pruned_args_dispatch, n),\n name=f\"jit_simple_pruned_args_dispatch_{n}\"),\n google_benchmark.register(partial(jit_simple_pruned_args, n),\n name=f\"jit_simple_pruned_args_{n}\")\n ]\n\n\n@google_benchmark.register\ndef jit_dispatch_without_transfer(state):\n # We pick up a realistic input. 224 is usual for classification and 128 a\n # TPU-friendly batch-size.\n imgs = np.ones((128, 224, 224), np.float32)\n imgs = jax.device_put(imgs)\n\n f = jax.jit(lambda x: x+1)\n f(imgs)\n\n while state:\n f(imgs)\n\n\n@google_benchmark.register\ndef jit_dispatch_with_transfer(state):\n imgs = np.ones((128, 224, 224), np.float32)\n\n f = jax.jit(lambda x: x+1)\n f(imgs).block_until_ready()\n\n while state:\n x = f(imgs)\n x.block_until_ready()\n\n\n@google_benchmark.register\n@required_devices(2)\ndef pmap_trivial_2_devices(state):\n f = jax.pmap(swap)\n a, b = f(jnp.array([1, 2]), jnp.array([3, 4]))\n\n while state:\n c, d = f(a, b)\n c.block_until_ready()\n d.block_until_ready()\n\n\n@google_benchmark.register\n@required_devices(8)\ndef pmap_trivial_dispatch_8_devices(state):\n f = jax.pmap(swap)\n a, b = f(jnp.array([1, 2, 3, 4, 5, 6, 7, 8]),\n jnp.array([2, 3, 4, 5, 6, 7, 8, 9]))\n\n while state:\n a, b = f(a, b)\n\n\n@google_benchmark.register\n@required_devices(8)\ndef pmap_trivial_8_devices(state):\n f = jax.pmap(swap)\n a, b = f(jnp.array([1, 2, 3, 4, 5, 6, 7, 8]),\n jnp.array([2, 3, 4, 5, 6, 7, 8, 9]))\n\n while state:\n c, d = f(a, b)\n c.block_until_ready()\n d.block_until_ready()\n\n\n@google_benchmark.register\n@required_devices(2)\ndef pmap_simple_2_devices(state):\n f = jax.pmap(lambda a, b: (a + b, a - b))\n a, b = f(jnp.array([1, 2]), jnp.array([3, 4]))\n\n while state:\n c, d = f(a, b)\n c.block_until_ready()\n d.block_until_ready()\n\n\n@google_benchmark.register\n@required_devices(8)\ndef pmap_simple_dispatch_8_devices(state):\n f = jax.pmap(lambda a, b: (a + b, a - b))\n a, b = f(jnp.array([1, 2, 3, 4, 5, 6, 7, 8]),\n jnp.array([2, 3, 4, 5, 6, 7, 8, 9]))\n\n while state:\n a, b = f(a, b)\n\n\n@google_benchmark.register\n@required_devices(8)\ndef pmap_simple_8_devices(state):\n f = jax.pmap(lambda a, b: (a + b, a - b))\n a, b = f(jnp.array([1, 2, 3, 4, 5, 6, 7, 8]),\n jnp.array([2, 3, 4, 5, 6, 7, 8, 9]))\n\n while state:\n c, d = f(a, b)\n c.block_until_ready()\n d.block_until_ready()\n\n\n@google_benchmark.register\n@required_devices(8)\ndef pmap_simple_dispatch_8_devices_100_args(state):\n f = jax.pmap(lambda *args: args[1:] + (args[0] + 1,))\n args = []\n for i in range(100):\n args.append(jnp.array(list(range(i, i+8))))\n\n args = f(*args)\n\n while state:\n args = f(*args)\n\n\n@google_benchmark.register\n@required_devices(8)\ndef pmap_simple_8_devices_100_args(state):\n f = jax.pmap(lambda *args: args[1:] + (args[0] + 1,))\n args = []\n for i in range(100):\n args.append(jnp.array(list(range(i, i+8))))\n\n # Warmup loop.\n out = f(*args)\n\n while state:\n out = f(*args)\n jax.tree_map(lambda x: x.block_until_ready(), out)\n\n\ndef _run_sda_index_bench(state, num_devices):\n x = jax.pmap(jnp.sin)(jnp.arange(num_devices))\n jax.device_get(x)\n while state:\n for i in range(num_devices):\n _ = x[i]\n\n\n@google_benchmark.register\n@required_devices(1)\ndef sda_index_1(state):\n _run_sda_index_bench(state, 1)\n\n\n@google_benchmark.register\n@required_devices(2)\ndef sda_index_2(state):\n _run_sda_index_bench(state, 2)\n\n\n@google_benchmark.register\n@required_devices(8)\ndef sda_index_8(state):\n _run_sda_index_bench(state, 8)\n\n\ndef swap(a, b):\n return b, a\n\n\nif __name__ == \"__main__\":\n google_benchmark.main()\n"
] | [
[
"numpy.ones"
]
] |
Puneet-G/Impersonator-NNProject | [
"980cfc260feebbc873b4150326791340f6526c42"
] | [
"thirdparty/his_evaluators/tests/metric_test.py"
] | [
"import torch\nimport numpy as np\nimport unittest\n\n\nfrom his_evaluators.metrics import register_metrics\n\n\nDEVICE = torch.device(\"cuda:0\")\n\n\nclass MetricTestCase(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls) -> None:\n cls.paired_metric_dict = register_metrics(types=(\"ssim\", \"psnr\", \"lps\"), device=DEVICE)\n cls.unpaired_metric_dict = register_metrics(\n types=(\"is\", \"fid\", \"PCB-CS-reid\", \"PCB-freid\", \"OS-CS-reid\", \"OS-freid\"),\n device=DEVICE\n )\n\n def test_01_paired_metrics(self):\n bs = 5\n image_size = 512\n preds_imgs = np.random.rand(bs, 3, image_size, image_size)\n preds_imgs *= 255\n preds_imgs = preds_imgs.astype(np.uint8)\n ref_imgs = np.copy(preds_imgs)\n\n ssim_score = self.paired_metric_dict[\"ssim\"].calculate_score(preds_imgs, ref_imgs)\n psnr_score = self.paired_metric_dict[\"psnr\"].calculate_score(preds_imgs, ref_imgs)\n lps_score = self.paired_metric_dict[\"lps\"].calculate_score(preds_imgs, ref_imgs)\n\n print(\"ssim score = {}\".format(ssim_score))\n print(\"psnr score = {}\".format(psnr_score))\n print(\"lps score = {}\".format(lps_score))\n\n self.assertEqual(ssim_score, 1.0)\n self.assertEqual(psnr_score, np.inf)\n self.assertEqual(lps_score, 0.0)\n\n def test_02_unpaired_metrics(self):\n bs = 5\n image_size = 512\n preds_imgs = np.random.rand(bs, 3, image_size, image_size)\n preds_imgs *= 255\n preds_imgs = preds_imgs.astype(np.uint8)\n\n ref_imgs = np.random.rand(bs, 3, image_size, image_size)\n ref_imgs *= 255\n ref_imgs = ref_imgs.astype(np.uint8)\n\n inception_score = self.unpaired_metric_dict[\"is\"].calculate_score(preds_imgs)\n fid_score = self.unpaired_metric_dict[\"fid\"].calculate_score(preds_imgs, ref_imgs)\n os_cs_reid = self.unpaired_metric_dict[\"OS-CS-reid\"].calculate_score(preds_imgs, ref_imgs)\n pcb_cs_reid = self.unpaired_metric_dict[\"PCB-CS-reid\"].calculate_score(preds_imgs, ref_imgs)\n os_freid = self.unpaired_metric_dict[\"OS-freid\"].calculate_score(preds_imgs, ref_imgs)\n pcb_freid = self.unpaired_metric_dict[\"PCB-freid\"].calculate_score(preds_imgs, ref_imgs)\n\n print(\"inception score = {}\".format(inception_score))\n print(\"fid score = {}\".format(fid_score))\n print(\"OS-Cosine Similarity = {}\".format(os_cs_reid))\n print(\"PCB-Cosine Similarity = {}\".format(pcb_cs_reid))\n print(\"OS-freid = {}\".format(os_freid))\n print(\"PCB-freid = {}\".format(pcb_freid))\n\n\nif __name__ == '__main__':\n unittest.main()\n"
] | [
[
"torch.device",
"numpy.random.rand",
"numpy.copy"
]
] |
elcolie/sklearn-onnx | [
"004fa39cb995ada0cde232ae8e30341018f450ac",
"004fa39cb995ada0cde232ae8e30341018f450ac"
] | [
"docs/examples/plot_custom_model.py",
"tests/test_sklearn_double_tensor_type_reg.py"
] | [
"# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\n\"\"\"\n.. _l-custom-model:\n\nWrite your own converter for your own model\n===========================================\n\nIt might happen that you implemented your own model\nand there is obviously no existing converter for this\nnew model. That does not mean the conversion of a pipeline\nwhich includes it would not work. Let's see how to do it.\n\n`t-SNE <https://lvdmaaten.github.io/tsne/>`_ is an interesting\ntransform which can only be used to study data as there is no\nway to reproduce the result once it was fitted. That's why\nthe class `TSNE <https://scikit-learn.org/stable/modules/\ngenerated/sklearn.manifold.TSNE.html>`_\ndoes not have any method *transform*, only\n`fit_transform <https://scikit-learn.org/stable/modules/\ngenerated/sklearn.manifold.TSNE.html#sklearn.manifold.TSNE.fit_transform>`_.\nThis example proposes a way to train a machine learned model\nwhich approximates the outputs of a *t-SNE* transformer.\n\n\n.. contents::\n :local:\n\nImplementation of the new transform\n+++++++++++++++++++++++++++++++++++\n\nThe first section is about the implementation.\nThe code is quite generic but basically follows this\nprocess to fit the model with *X* and *y*:\n\n* t-SNE, :math:`(X, y) \\\\rightarrow X_2 \\\\in \\\\mathbb{R}^2`\n* k nearest neightbours, :math:`fit(X, X_2)`,\n which produces function :math:`f(X) \\\\rightarrow X_3`\n* final normalization, simple scaling :math:`X_3 \\\\rightarrow X_4`\n\nAnd to predict on a test set:\n\n* k nearest neightbours, :math:`f(X') \\\\rightarrow X'_3`\n* final normalization, simple scaling :math:`X'_3 \\\\rightarrow X'_4`\n\"\"\"\nimport inspect\nimport os\nimport numpy\nimport onnx\nfrom onnx.tools.net_drawer import GetPydotGraph, GetOpNodeProducer\nimport onnxruntime as rt\nfrom matplotlib import offsetbox\nimport matplotlib.pyplot as plt\nimport sklearn\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import datasets\nfrom sklearn.base import BaseEstimator, TransformerMixin, clone\nfrom sklearn.manifold import TSNE\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom skl2onnx import update_registered_converter\nimport skl2onnx\nfrom skl2onnx import convert_sklearn, get_model_alias\nfrom skl2onnx.common._registration import get_shape_calculator\nfrom skl2onnx.common.data_types import FloatTensorType\n\n\nclass PredictableTSNE(BaseEstimator, TransformerMixin):\n\n def __init__(self, transformer=None, estimator=None,\n normalize=True, keep_tsne_outputs=False, **kwargs):\n \"\"\"\n :param transformer: `TSNE` by default\n :param estimator: `MLPRegressor` by default\n :param normalize: normalizes the outputs, centers and normalizes\n the output of the *t-SNE* and applies that same\n normalization to he prediction of the estimator\n :param keep_tsne_output: if True, keep raw outputs of\n *TSNE* is stored in member *tsne_outputs_*\n :param kwargs: sent to :meth:`set_params <mlinsights.mlmodel.\n tsne_transformer.PredictableTSNE.set_params>`, see its\n documentation to understand how to specify parameters\n \"\"\"\n TransformerMixin.__init__(self)\n BaseEstimator.__init__(self)\n if estimator is None:\n estimator = KNeighborsRegressor()\n if transformer is None:\n transformer = TSNE()\n self.estimator = estimator\n self.transformer = transformer\n self.keep_tsne_outputs = keep_tsne_outputs\n if not hasattr(transformer, \"fit_transform\"):\n raise AttributeError(\n \"Transformer {} does not have a 'fit_transform' \"\n \"method.\".format(type(transformer)))\n if not hasattr(estimator, \"predict\"):\n raise AttributeError(\n \"Estimator {} does not have a 'predict' method.\".format(\n type(estimator)))\n self.normalize = normalize\n if kwargs:\n self.set_params(**kwargs)\n\n def fit(self, X, y, sample_weight=None):\n \"\"\"\n Runs a *k-means* on each class\n then trains a classifier on the\n extended set of features.\n Parameters\n ----------\n X : numpy array or sparse matrix of shape [n_samples,n_features]\n Training data\n y : numpy array of shape [n_samples, n_targets]\n Target values. Will be cast to X's dtype if necessary\n sample_weight : numpy array of shape [n_samples]\n Individual weights for each sample\n Returns\n -------\n self : returns an instance of self.\n Attributes\n ----------\n transformer_: trained transformeer\n estimator_: trained regressor\n tsne_outputs_: t-SNE outputs if *keep_tsne_outputs* is True\n mean_: average of the *t-SNE* output on each dimension\n inv_std_: inverse of the standard deviation of the *t-SNE*\n output on each dimension\n loss_: loss (*mean_squared_error*)\n between the predictions and the outputs of t-SNE\n \"\"\"\n params = dict(y=y, sample_weight=sample_weight)\n\n self.transformer_ = clone(self.transformer)\n\n sig = inspect.signature(self.transformer.fit_transform)\n pars = {}\n for p in ['sample_weight', 'y']:\n if p in sig.parameters and p in params:\n pars[p] = params[p]\n target = self.transformer_.fit_transform(X, **pars)\n\n sig = inspect.signature(self.estimator.fit)\n if 'sample_weight' in sig.parameters:\n self.estimator_ = clone(self.estimator).fit(\n X, target, sample_weight=sample_weight)\n else:\n self.estimator_ = clone(self.estimator).fit(X, target)\n mean = target.mean(axis=0)\n var = target.std(axis=0)\n self.mean_ = mean\n self.inv_std_ = 1. / var\n exp = (target - mean) * self.inv_std_\n got = (self.estimator_.predict(X) - mean) * self.inv_std_\n self.loss_ = mean_squared_error(exp, got)\n if self.keep_tsne_outputs:\n self.tsne_outputs_ = exp if self.normalize else target\n return self\n\n def transform(self, X):\n \"\"\"\n Runs the predictions.\n Parameters\n ----------\n X : numpy array or sparse matrix of shape [n_samples,n_features]\n Training data\n Returns\n -------\n tranformed *X*\n \"\"\"\n pred = self.estimator_.predict(X)\n if self.normalize:\n pred -= self.mean_\n pred *= self.inv_std_\n return pred\n\n def get_params(self, deep=True):\n \"\"\"\n Returns the parameters for all the embedded objects.\n \"\"\"\n res = {}\n for k, v in self.transformer.get_params().items():\n res[\"t_\" + k] = v\n for k, v in self.estimator.get_params().items():\n res[\"e_\" + k] = v\n return res\n\n def set_params(self, **values):\n \"\"\"\n Sets the parameters before training.\n Every parameter prefixed by ``'e_'`` is an estimator\n parameter, every parameter prefixed by\n ``t_`` is for a transformer parameter.\n \"\"\"\n pt, pe, pn = {}, {}, {}\n for k, v in values.items():\n if k.startswith('e_'):\n pe[k[2:]] = v\n elif k.startswith('t_'):\n pt[k[2:]] = v\n elif k.startswith('n_'):\n pn[k[2:]] = v\n else:\n raise ValueError(\"Unexpected parameter name '{0}'.\".format(k))\n self.transformer.set_params(**pt)\n self.estimator.set_params(**pe)\n\n\n###########################\n# Experimentation on MNIST\n# ++++++++++++++++++++++++\n#\n# Let's fit t-SNE...\n\n\ndigits = datasets.load_digits(n_class=6)\nXd = digits.data\nyd = digits.target\nimgs = digits.images\nn_samples, n_features = Xd.shape\nn_samples, n_features\n\nX_train, X_test, y_train, y_test, imgs_train, imgs_test = train_test_split(\n Xd, yd, imgs)\n\ntsne = TSNE(n_components=2, init='pca', random_state=0)\n\n\ndef plot_embedding(Xp, y, imgs, title=None, figsize=(12, 4)):\n x_min, x_max = numpy.min(Xp, 0), numpy.max(Xp, 0)\n X = (Xp - x_min) / (x_max - x_min)\n\n fig, ax = plt.subplots(1, 2, figsize=figsize)\n for i in range(X.shape[0]):\n ax[0].text(X[i, 0], X[i, 1], str(y[i]),\n color=plt.cm.Set1(y[i] / 10.),\n fontdict={'weight': 'bold', 'size': 9})\n\n if hasattr(offsetbox, 'AnnotationBbox'):\n # only print thumbnails with matplotlib > 1.0\n shown_images = numpy.array([[1., 1.]]) # just something big\n for i in range(X.shape[0]):\n dist = numpy.sum((X[i] - shown_images) ** 2, 1)\n if numpy.min(dist) < 4e-3:\n # don't show points that are too close\n continue\n shown_images = numpy.r_[shown_images, [X[i]]]\n imagebox = offsetbox.AnnotationBbox(\n offsetbox.OffsetImage(imgs[i], cmap=plt.cm.gray_r),\n X[i])\n ax[0].add_artist(imagebox)\n ax[0].set_xticks([]), ax[0].set_yticks([])\n ax[1].plot(Xp[:, 0], Xp[:, 1], '.')\n if title is not None:\n ax[0].set_title(title)\n return ax\n\n\nX_train_tsne = tsne.fit_transform(X_train)\nplot_embedding(X_train_tsne, y_train, imgs_train,\n \"t-SNE embedding of the digits\")\n\n#######################################\n# Repeatable t-SNE\n# ++++++++++++++++\n#\n# Just to check it is working.\n\nptsne_knn = PredictableTSNE()\nptsne_knn.fit(X_train, y_train)\n\nX_train_tsne2 = ptsne_knn.transform(X_train)\nplot_embedding(X_train_tsne2, y_train, imgs_train,\n \"Predictable t-SNE of the digits\\n\"\n \"StandardScaler+KNeighborsRegressor\")\n\n################################\n# We check on test set.\n\n\nX_test_tsne2 = ptsne_knn.transform(X_test)\nplot_embedding(X_test_tsne2, y_test, imgs_test,\n \"Predictable t-SNE of the digits\\n\"\n \"StandardScaler+KNeighborsRegressor\")\n\n#######################################\n# ONNX - shape_calculator, converter\n# ++++++++++++++++++++++++++++++++++\n#\n# Now starts the part dedicated to *ONNX*.\n# *ONNX* conversion requires two function,\n# one to calculate the shape of the outputs based\n# on the inputs, the other one to do the actual\n# conversion of the model.\n\n\ndef predictable_tsne_shape_calculator(operator):\n\n input = operator.inputs[0] # inputs in ONNX graph\n # output = operator.outputs[0] # output in ONNX graph\n op = operator.raw_operator # scikit-learn model (mmust be fitted)\n\n N = input.type.shape[0] # number of observations\n C = op.estimator_._y.shape[1] # dimension of outputs\n\n # new output definition\n operator.outputs[0].type = FloatTensorType([N, C])\n\n\n##################################\n# Then the converter model. We\n# reuse existing converter.\n\n\ndef predictable_tsne_converter(scope, operator, container):\n \"\"\"\n :param scope: name space, where to keep node names, get unused new names\n :param operator: operator to converter, same object as sent to\n *predictable_tsne_shape_calculator*\n :param container: contains the ONNX graph\n \"\"\"\n # input = operator.inputs[0] # input in ONNX graph\n output = operator.outputs[0] # output in ONNX graph\n op = operator.raw_operator # scikit-learn model (mmust be fitted)\n\n # First step is the k nearest-neighbours,\n # we reuse existing converter and declare it as local\n # operator.\n model = op.estimator_\n alias = get_model_alias(type(model))\n knn_op = scope.declare_local_operator(alias, model)\n knn_op.inputs = operator.inputs\n\n # We add an intermediate outputs.\n knn_output = scope.declare_local_variable('knn_output', FloatTensorType())\n knn_op.outputs.append(knn_output)\n\n # We adjust the output of the submodel.\n shape_calc = get_shape_calculator(alias)\n shape_calc(knn_op)\n\n # We add the normalizer which needs a unique node name.\n name = scope.get_unique_operator_name('Scaler')\n\n # The parameter follows the specifications of ONNX\n # https://github.com/onnx/onnx/blob/master/docs/Operators-ml.md#ai.onnx.ml.Scaler\n attrs = dict(name=name,\n scale=op.inv_std_.ravel().astype(numpy.float32),\n offset=op.mean_.ravel().astype(numpy.float32))\n\n # Let's finally add the scaler which connects the output\n # of the k-nearest neighbours model to output of the whole model\n # declared in ONNX graph\n container.add_node('Scaler', [knn_output.onnx_name], [output.full_name],\n op_domain='ai.onnx.ml', **attrs)\n\n##################################\n# We now need to declare the new converter.\n\n\nupdate_registered_converter(PredictableTSNE, 'CustomPredictableTSNE',\n predictable_tsne_shape_calculator,\n predictable_tsne_converter)\n\n####################################\n# Conversion to ONNX\n# ++++++++++++++++++\n#\n# We just need to call *convert_sklearn* as any other model\n# to convert.\n\nmodel_onnx = convert_sklearn(\n ptsne_knn, 'predictable_tsne',\n [('input', FloatTensorType([None, X_test.shape[1]]))],\n target_opset=12)\n\n# And save.\nwith open(\"predictable_tsne.onnx\", \"wb\") as f:\n f.write(model_onnx.SerializeToString())\n\n##################################\n# We now compare the prediction.\n\nprint(\"ptsne_knn.tranform\\n\", ptsne_knn.transform(X_test[:2]))\n\n##########################\n# Predictions with onnxruntime.\n\nsess = rt.InferenceSession(\"predictable_tsne.onnx\")\n\npred_onx = sess.run(None, {\"input\": X_test[:1].astype(numpy.float32)})\nprint(\"transform\", pred_onx[0])\n\n##################################\n# The converter for the nearest neighbours produces an ONNX graph\n# which does not allow multiple predictions at a time. Let's call\n# *onnxruntime* for the second row.\n\npred_onx = sess.run(None, {\"input\": X_test[1:2].astype(numpy.float32)})\nprint(\"transform\", pred_onx[0])\n\n##################################\n# Display the ONNX graph\n# ++++++++++++++++++++++\n\npydot_graph = GetPydotGraph(\n model_onnx.graph, name=model_onnx.graph.name, rankdir=\"TB\",\n node_producer=GetOpNodeProducer(\n \"docstring\", color=\"yellow\", fillcolor=\"yellow\", style=\"filled\"))\npydot_graph.write_dot(\"pipeline_tsne.dot\")\n\nos.system('dot -O -Gdpi=300 -Tpng pipeline_tsne.dot')\n\nimage = plt.imread(\"pipeline_tsne.dot.png\")\nfig, ax = plt.subplots(figsize=(40, 20))\nax.imshow(image)\nax.axis('off')\n\n#################################\n# **Versions used for this example**\n\nprint(\"numpy:\", numpy.__version__)\nprint(\"scikit-learn:\", sklearn.__version__)\nprint(\"onnx: \", onnx.__version__)\nprint(\"onnxruntime: \", rt.__version__)\nprint(\"skl2onnx: \", skl2onnx.__version__)\n",
"\"\"\"Tests GLMRegressor converter.\"\"\"\r\n\r\nimport unittest\r\nfrom distutils.version import StrictVersion\r\nimport numpy as np\r\nfrom sklearn.exceptions import ConvergenceWarning\r\ntry:\r\n from sklearn.utils._testing import ignore_warnings\r\nexcept ImportError:\r\n from sklearn.utils.testing import ignore_warnings\r\nfrom sklearn.ensemble import BaggingRegressor\r\nfrom sklearn.gaussian_process import GaussianProcessRegressor\r\nfrom sklearn.linear_model import LinearRegression, SGDRegressor\r\nfrom sklearn.neighbors import KNeighborsRegressor\r\nfrom sklearn.neural_network import MLPRegressor\r\ntry:\r\n from sklearn.ensemble import VotingRegressor\r\nexcept ImportError:\r\n # New in 0.21\r\n VotingRegressor = None\r\nfrom skl2onnx import convert_sklearn, to_onnx\r\nfrom skl2onnx.common.data_types import DoubleTensorType\r\nfrom onnxruntime import __version__ as ort_version\r\nfrom test_utils import (\r\n dump_data_and_model, fit_regression_model, TARGET_OPSET)\r\n\r\nwarnings_to_skip = (DeprecationWarning, FutureWarning, ConvergenceWarning)\r\n\r\n\r\nclass TestSklearnDoubleTensorTypeRegressor(unittest.TestCase):\r\n @unittest.skipIf(\r\n StrictVersion(ort_version) <= StrictVersion(\"1.2.0\"),\r\n reason=\"onnxruntime misses implementation for double\")\r\n @ignore_warnings(category=warnings_to_skip)\r\n def test_model_linear_regression_64(self):\r\n model, X = fit_regression_model(LinearRegression())\r\n model_onnx = convert_sklearn(\r\n model, \"linear regression\",\r\n [(\"input\", DoubleTensorType([None, X.shape[1]]))],\r\n target_opset=TARGET_OPSET)\r\n self.assertIn(\"elem_type: 11\", str(model_onnx))\r\n dump_data_and_model(\r\n X.astype(np.float64), model, model_onnx,\r\n basename=\"SklearnLinearRegressionDouble\")\r\n\r\n @unittest.skipIf(\r\n StrictVersion(ort_version) < StrictVersion(\"1.7.0\"),\r\n reason=\"onnxruntime misses implementation for \"\r\n \"Relu, Tanh, Sigmoid for double\")\r\n @ignore_warnings(category=warnings_to_skip)\r\n def test_model_mlpregressor_64(self):\r\n # Could not find an implementation for the node Relu:Relu(6)\r\n # Could not find an implementation for the node Tanh:Tanh(6)\r\n # Could not find an implementation for the node Sigmoid:Sigmoid(6)\r\n for activation in ['relu', 'tanh', 'logistic']:\r\n with self.subTest(activation=activation):\r\n model, X = fit_regression_model(\r\n MLPRegressor(activation=activation))\r\n model_onnx = convert_sklearn(\r\n model, \"linear regression\",\r\n [(\"input\", DoubleTensorType([None, X.shape[1]]))],\r\n target_opset=TARGET_OPSET)\r\n self.assertIn(\"elem_type: 11\", str(model_onnx))\r\n dump_data_and_model(\r\n X.astype(np.float64), model, model_onnx,\r\n basename=\"SklearnMLPRegressorDouble%s\" % activation)\r\n\r\n @unittest.skipIf(\r\n StrictVersion(ort_version) < StrictVersion(\"1.7.0\"),\r\n reason=\"onnxruntime misses implementation for \"\r\n \"ReduceMean for double\")\r\n @ignore_warnings(category=warnings_to_skip)\r\n def test_bagging_regressor_sgd_64(self):\r\n # Could not find an implementation for\r\n # the node ReduceMean:ReduceMean(11)\r\n model, X = fit_regression_model(\r\n BaggingRegressor(SGDRegressor()))\r\n model_onnx = convert_sklearn(\r\n model, \"bagging regressor\",\r\n [(\"input\", DoubleTensorType([None, X.shape[1]]))],\r\n target_opset=TARGET_OPSET)\r\n dump_data_and_model(\r\n X.astype(np.float64), model, model_onnx,\r\n basename=\"SklearnBaggingRegressorSGDDouble\")\r\n\r\n @unittest.skipIf(\r\n StrictVersion(ort_version) <= StrictVersion(\"1.2.0\"),\r\n reason=\"onnxruntime misses implementation for double\")\r\n @ignore_warnings(category=warnings_to_skip)\r\n def test_model_sgd_regressor_64(self):\r\n model, X = fit_regression_model(SGDRegressor())\r\n model_onnx = convert_sklearn(\r\n model, \"linear regression\",\r\n [(\"input\", DoubleTensorType([None, X.shape[1]]))],\r\n target_opset=TARGET_OPSET)\r\n self.assertIn(\"elem_type: 11\", str(model_onnx))\r\n dump_data_and_model(\r\n X.astype(np.float64), model, model_onnx,\r\n basename=\"SklearnLinearSGDRegressorDouble\")\r\n\r\n @unittest.skipIf(\r\n StrictVersion(ort_version) < StrictVersion(\"1.7.0\"),\r\n reason=\"shape_inference fails\")\r\n @ignore_warnings(category=warnings_to_skip)\r\n def test_gpr_rbf_fitted_true_double(self):\r\n gp = GaussianProcessRegressor(\r\n alpha=1e-7, n_restarts_optimizer=15, normalize_y=True)\r\n gp, X = fit_regression_model(gp)\r\n model_onnx = to_onnx(\r\n gp, initial_types=[('X', DoubleTensorType([None, None]))],\r\n target_opset=TARGET_OPSET)\r\n dump_data_and_model(\r\n X.astype(np.float64), gp, model_onnx, verbose=False,\r\n basename=\"SklearnGaussianProcessRBFTDouble\")\r\n\r\n @unittest.skipIf(\r\n StrictVersion(ort_version) < StrictVersion(\"1.7.0\"),\r\n reason=\"onnxruntime misses implementation for \"\r\n \"TopK for double\")\r\n @ignore_warnings(category=warnings_to_skip)\r\n def test_model_knn_regressor_double(self):\r\n # Could not find an implementation for the node To_TopK:TopK(11)\r\n model, X = fit_regression_model(KNeighborsRegressor(n_neighbors=2))\r\n model_onnx = convert_sklearn(\r\n model, \"KNN regressor\", [(\"input\", DoubleTensorType([None, 4]))],\r\n target_opset=TARGET_OPSET,\r\n options={id(model): {'optim': 'cdist'}})\r\n dump_data_and_model(\r\n X.astype(np.float64)[:7],\r\n model, model_onnx,\r\n basename=\"SklearnKNeighborsRegressorDouble\")\r\n\r\n @unittest.skipIf(VotingRegressor is None, reason=\"new in 0.21\")\r\n @unittest.skipIf(\r\n StrictVersion(ort_version) < StrictVersion(\"1.7.0\"),\r\n reason=\"onnxruntime misses implementation for \"\r\n \"Sum for double\")\r\n @ignore_warnings(category=warnings_to_skip)\r\n def test_model_voting_regression(self):\r\n # Could not find an implementation for the node Sum:Sum(8)\r\n model = VotingRegressor([\r\n ('lr', LinearRegression()),\r\n ('dt', SGDRegressor())])\r\n model, X = fit_regression_model(model)\r\n model_onnx = convert_sklearn(\r\n model, \"voting regression\",\r\n [(\"input\", DoubleTensorType([None, X.shape[1]]))],\r\n target_opset=TARGET_OPSET)\r\n dump_data_and_model(\r\n X.astype(np.float64), model, model_onnx,\r\n basename=\"SklearnVotingRegressorDouble\",\r\n comparable_outputs=[0])\r\n\r\n\r\nif __name__ == \"__main__\":\r\n unittest.main()\r\n"
] | [
[
"matplotlib.pyplot.imread",
"sklearn.base.BaseEstimator.__init__",
"numpy.sum",
"sklearn.base.clone",
"sklearn.metrics.mean_squared_error",
"sklearn.neighbors.KNeighborsRegressor",
"matplotlib.offsetbox.OffsetImage",
"matplotlib.pyplot.subplots",
"sklearn.manifold.TSNE",
"matplotlib.pyplot.cm.Set1",
"numpy.max",
"sklearn.base.TransformerMixin.__init__",
"numpy.min",
"numpy.array",
"sklearn.datasets.load_digits",
"sklearn.model_selection.train_test_split"
],
[
"sklearn.neighbors.KNeighborsRegressor",
"sklearn.linear_model.SGDRegressor",
"sklearn.linear_model.LinearRegression",
"sklearn.utils.testing.ignore_warnings",
"sklearn.neural_network.MLPRegressor",
"sklearn.gaussian_process.GaussianProcessRegressor"
]
] |
c-hydro/door | [
"de6ebcbe69289425ae13d85286dcd8da270e787e"
] | [
"gefs/door_downloader_nwp_gefs_nomads.py"
] | [
"#!/usr/bin/python3\n\n\"\"\"\nHyDE Downloading Tool - NWP GEFS 0.25\n\n__date__ = '20210914'\n__version__ = '1.0.0'\n__author__ =\n 'Andrea Libertino ([email protected]',\n 'Fabio Delogu ([email protected]',\n__library__ = 'HyDE'\n\nGeneral command line:\npython3 hyde_downloader_nwp_gefs_nomads.py -settings_file configuration.json -time YYYY-MM-DD HH:MM\n\nVersion(s):\n20200227 (1.0.0) --> Beta release\n\"\"\"\n# -------------------------------------------------------------------------------------\n\n# -------------------------------------------------------------------------------------\n# Complete library\nimport logging\nimport os\nimport time\nimport json\nimport urllib.request\nimport tempfile\nimport xarray as xr\n\nimport numpy as np\nimport pandas as pd\n\nfrom urllib.request import Request, urlopen\nfrom urllib.error import URLError\n\nfrom copy import deepcopy\nfrom cdo import Cdo\nfrom multiprocessing import Pool, cpu_count\nfrom datetime import datetime\nfrom os import makedirs\nfrom os.path import join, exists, split\nfrom argparse import ArgumentParser\n# -------------------------------------------------------------------------------------\n\n# -------------------------------------------------------------------------------------\n# Algorithm information\nalg_name = 'HYDE DOWNLOADING TOOL - NWP GEFS'\nalg_version = '1.0.0'\nalg_release = '2021-09-14'\n# Algorithm parameter(s)\ntime_format = '%Y%m%d%H%M'\n# -------------------------------------------------------------------------------------\n\n\n# -------------------------------------------------------------------------------------\n# Script Main\ndef main():\n\n # -------------------------------------------------------------------------------------\n # Get algorithm settings\n alg_settings, alg_time = get_args()\n\n # Set algorithm settings\n data_settings = read_file_json(alg_settings)\n\n # Set algorithm logging\n make_folder(data_settings['data']['log']['folder'])\n set_logging(logger_file=join(data_settings['data']['log']['folder'], data_settings['data']['log']['filename']))\n # -------------------------------------------------------------------------------------\n\n # -------------------------------------------------------------------------------------\n # Info algorithm\n logging.info(' ============================================================================ ')\n logging.info(' ==> ' + alg_name + ' (Version: ' + alg_version + ' Release_Date: ' + alg_release + ')')\n logging.info(' ==> START ... ')\n logging.info(' ')\n\n # Time algorithm information\n start_time = time.time()\n # -------------------------------------------------------------------------------------\n\n # -------------------------------------------------------------------------------------\n # Get algorithm time range\n time_run, time_run_range = set_run_time(alg_time, data_settings['time'])\n ens_members = np.arange(1,data_settings[\"algorithm\"][\"ancillary\"][\"ens_members\"]+1)\n\n # Starting info\n logging.info(' --> TIME RUN: ' + str(time_run))\n\n\n # Iterate over time steps\n for time_run_step in time_run_range:\n\n # Starting info\n logging.info(' ---> NWP RUN: ' + str(time_run_step) + ' ... ')\n\n # Iterate over ensemble members\n for ens_member in ens_members:\n\n # Starting info\n logging.info(' ---> ENSEMBLE MEMBER: ' + str(ens_member).zfill(2) + ' ... ')\n\n # Get data time range\n time_data_range = set_data_time(time_run_step, data_settings['data']['dynamic']['time'])\n time_data_full = pd.date_range(time_run + pd.Timedelta('1H'), time_data_range[-1], freq='1H')\n\n # Set data sources\n data_source = set_data_source(time_run_step, time_data_range, ens_member,\n data_settings['data']['dynamic']['source'],\n data_settings['data']['static']['bounding_box'],\n data_settings['algorithm']['ancillary'],\n data_settings['algorithm']['template'],\n type_data=data_settings['algorithm']['ancillary']['type'],)\n # Set data ancillary\n data_ancillary = set_data_ancillary(time_run_step, time_data_range, ens_member,\n data_settings['data']['dynamic']['ancillary'],\n data_settings['data']['static']['bounding_box'],\n data_settings['algorithm']['ancillary'],\n data_settings['algorithm']['template'],\n type_data=data_settings['algorithm']['ancillary']['type'],)\n\n # Set data outcome global\n data_outcome_global = set_data_outcome(\n time_run_step, ens_member,\n data_settings['data']['dynamic']['outcome']['global'],\n data_settings['data']['static']['bounding_box'],\n data_settings['algorithm']['ancillary'],\n data_settings['algorithm']['template'],\n type_data=data_settings['algorithm']['ancillary']['type'],\n flag_updating=data_settings['algorithm']['flags']['cleaning_dynamic_data_global'])\n\n # Set data outcome domain\n data_outcome_domain = set_data_outcome(\n time_run_step, ens_member,\n data_settings['data']['dynamic']['outcome']['domain'],\n data_settings['data']['static']['bounding_box'],\n data_settings['algorithm']['ancillary'],\n data_settings['algorithm']['template'],\n type_data=data_settings['algorithm']['ancillary']['type'],\n flag_updating=data_settings['algorithm']['flags']['cleaning_dynamic_data_domain'])\n\n if data_settings['algorithm']['flags']['downloading_mp']:\n retrieve_data_source_mp(\n data_source, data_ancillary,\n flag_updating=data_settings['algorithm']['flags']['cleaning_dynamic_data_ancillary'],\n process_n=data_settings['algorithm']['ancillary']['process_mp'], limit=data_settings['algorithm']['ancillary']['remote_server_hit_per_min'])\n else:\n retrieve_data_source_seq(\n data_source, data_ancillary,\n flag_updating=data_settings['algorithm']['flags']['cleaning_dynamic_data_ancillary'], limit=data_settings['algorithm']['ancillary']['remote_server_hit_per_min'])\n\n # Merge and mask data ancillary to data outcome\n arrange_data_outcome(data_ancillary, data_outcome_global, data_outcome_domain,\n data_bbox=data_settings['data']['static']['bounding_box'],\n cdo_exec=data_settings['algorithm']['ancillary']['cdo_exec'],\n cdo_deps=data_settings['algorithm']['ancillary']['cdo_deps'],\n source_standards=data_settings['data']['dynamic']['source']['vars_standards'],\n date_range=time_data_full)\n\n # Clean data tmp (such as ancillary and outcome global)\n clean_data_tmp(\n data_ancillary, data_outcome_global,\n flag_cleaning_tmp=data_settings['algorithm']['flags']['cleaning_dynamic_data_tmp'])\n\n logging.info(' ---> ENSEMBLE MEMBER: ' + str(ens_member).zfill(2) + ' ... DONE')\n\n # Ending info\n logging.info(' ---> NWP RUN: ' + str(time_run_step) + ' ... DONE')\n # -------------------------------------------------------------------------------------\n\n # -------------------------------------------------------------------------------------\n # Info algorithm\n time_elapsed = round(time.time() - start_time, 1)\n\n logging.info(' ')\n logging.info(' ==> ' + alg_name + ' (Version: ' + alg_version + ' Release_Date: ' + alg_release + ')')\n logging.info(' ==> TIME ELAPSED: ' + str(time_elapsed) + ' seconds')\n logging.info(' ==> ... END')\n logging.info(' ==> Bye, Bye')\n logging.info(' ============================================================================ ')\n # -------------------------------------------------------------------------------------\n\n# -------------------------------------------------------------------------------------\n\n\n# -------------------------------------------------------------------------------------\n# Method to check source url(s)\ndef check_url_source(src_data, src_code_exist=200, process_n=20, process_max=None):\n\n logging.info(' ----> Checking source url(s) ... ')\n\n if process_max is None:\n process_max = cpu_count() - 1\n if process_n > process_max:\n logging.warning(' ----> Maximum of recommended processes must be less then ' + str(process_max))\n logging.warning(' ----> Set number of process from ' + str(process_n) + ' to ' + str(process_max))\n process_n = process_max\n\n src_response_list = []\n src_key_list = []\n for src_data_key, src_data_list in src_data.items():\n\n logging.info(' -----> Source ' + src_data_key + ' ... ')\n\n with Pool(processes=process_n, maxtasksperchild=1) as process_pool:\n src_response = process_pool.map(request_url, src_data_list, chunksize=1)\n process_pool.close()\n process_pool.join()\n src_response_list.append(src_response)\n\n src_key_list.append(src_data_key)\n logging.info(' -----> Source ' + src_data_key + ' ... DONE')\n\n for src_key_step, src_response_step in zip(src_key_list, src_response_list):\n if not all(src_code_el == src_code_exist for src_code_el in src_response_step):\n logging.warning(' ===> Some url(s) for source ' + src_key_step + ' are not available!')\n logging.info(' ----> Checking source url(s) ... FAILED')\n return False\n\n logging.info(' ----> Checking source url(s) ... DONE')\n return True\n\n# -------------------------------------------------------------------------------------\n\n\n# -------------------------------------------------------------------------------------\n# Method to request url\ndef request_url(src_url):\n logging.getLogger('requests').setLevel(logging.CRITICAL)\n src_request = Request(src_url)\n try:\n src_response = urlopen(src_request)\n return src_response.code\n except URLError as e:\n if hasattr(e, 'reason'):\n logging.warning(' ===> URL is unreachable from server.')\n logging.warning(' ===> URL: ', src_url[0])\n return False\n elif hasattr(e, 'code'):\n logging.warning(' ===> The server couldn\\'t fulfill the request.')\n logging.warning(' ===> URL: ', src_url[0])\n return False\n# -------------------------------------------------------------------------------------\n\n\n# -------------------------------------------------------------------------------------\n# Method to clean tmp data such as ancillary or global (if domain is set)\ndef clean_data_tmp(data_ancillary, data_outcome_global,\n flag_cleaning_tmp=False):\n\n if flag_cleaning_tmp:\n for data_key, data_value in data_ancillary.items():\n for data_step in data_value:\n if os.path.exists(data_step):\n os.remove(data_step)\n for data_key, data_value in data_outcome_global.items():\n for data_step in data_value:\n if os.path.exists(data_step):\n os.remove(data_step)\n# -------------------------------------------------------------------------------------\n\n\n# -------------------------------------------------------------------------------------\n# Method to merge and mask outcome dataset(s)\ndef arrange_data_outcome(src_data, dst_data_global, dst_data_domain,\n data_bbox=None, cdo_exec=None, cdo_deps=None, source_standards=None, date_range=None):\n\n logging.info(' ----> Dumping data ... ')\n\n if data_bbox is not None:\n bbox_lon_right = str(data_bbox['lon_right'])\n bbox_lon_left = str(data_bbox['lon_left'])\n bbox_lat_top = str(data_bbox['lat_top'])\n bbox_lat_bottom = str(data_bbox['lat_bottom'])\n\n bbox_points = [bbox_lon_left, bbox_lon_right, bbox_lat_bottom, bbox_lat_top]\n bbox_cdo = ','.join(bbox_points)\n else:\n bbox_cdo = None\n\n if cdo_exec is None:\n logging.error(' ===> CDO executable is not set!')\n raise RuntimeError(' CDO executable is not set!')\n\n for cdo_dep in cdo_deps:\n os.environ['LD_LIBRARY_PATH'] = 'LD_LIBRARY_PATH:' + cdo_dep\n #temp for local debug\n os.environ['PATH'] = os.environ['PATH'] + ':/home/andrea/FP_libs/fp_libs_cdo/cdo-1.9.8_nc-4.6.0_hdf-1.8.17_eccodes-2.17.0/bin/'\n\n cdo = Cdo()\n cdo.setCdo(cdo_exec)\n\n for (src_key_step, src_data_step), \\\n (dst_key_global_step, dst_data_global_step), (dst_key_domain_step, dst_data_domain_step) in \\\n zip(src_data.items(), dst_data_global.items(), dst_data_domain.items()):\n\n logging.info(' -----> Type ' + src_key_step + ' ... ')\n\n src_data_step.sort()\n if isinstance(dst_data_global_step, list):\n dst_data_global_step = dst_data_global_step[0]\n if isinstance(dst_data_domain_step, list):\n dst_data_domain_step = dst_data_domain_step[0]\n\n folder_data_global_step, filename_data_global_step = os.path.split(dst_data_global_step)\n tmp_data_global_step_cat = create_filename_tmp(folder=folder_data_global_step, suffix='.grib2')\n tmp_data_global_step_seltimestep = create_filename_tmp(folder=folder_data_global_step, suffix='.grib2')\n tmp_data_global_step_convert = create_filename_tmp(folder=folder_data_global_step, suffix='.nc')\n\n logging.info(' ------> Merge, convert and project data ... ')\n if not os.path.exists(dst_data_global_step):\n\n cdo.cat(input=src_data_step, output=tmp_data_global_step_cat, options='-r')\n info_file = cdo.infov(input=tmp_data_global_step_cat)\n\n # Explore available variable in the grib file, skiping rows with headers and footers\n var_in_all = [i.split(':')[-1].replace(' ','') for i in cdo.infov(input=tmp_data_global_step_cat) if i.split(':')[0].replace(' ','').isnumeric()]\n var_in = np.unique(var_in_all)\n logging.info(' ------> Var(s) found in file: ' + ','.join(var_in))\n\n step_expected = int(src_data_step.__len__()*len(var_in))\n step_get = len(var_in_all)\n\n if step_get > step_expected:\n step_ratio = int(step_get / step_expected)\n var_select_cdo, timestep_select_cdo = select_time_steps(\n info_file, id_start=step_ratio, id_end=step_get, id_period=step_ratio)\n cdo.seltimestep(timestep_select_cdo, input=tmp_data_global_step_cat, output=tmp_data_global_step_seltimestep)\n else:\n if os.path.exists(tmp_data_global_step_seltimestep):\n os.remove(tmp_data_global_step_seltimestep)\n tmp_data_global_step_seltimestep = tmp_data_global_step_cat\n\n cdo.copy(input=tmp_data_global_step_seltimestep, output=tmp_data_global_step_convert, options=\"-f nc4\")\n cdo.sellonlatbox('-180,180,-90,90', input=tmp_data_global_step_convert, output=dst_data_global_step)\n\n if not source_standards == None:\n\n if source_standards['convert2standard_continuum_format']:\n out_file = deepcopy(xr.open_dataset(dst_data_global_step))\n time_range_full = pd.date_range(min(out_file[\"time\"].values),max(out_file[\"time\"].values),freq='H')\n os.remove(dst_data_global_step)\n\n if '2t' in var_in.tolist():\n if source_standards['source_temperature_mesurement_unit'] == 'C':\n pass\n elif source_standards['source_temperature_mesurement_unit'] == 'K':\n logging.info(' ------> Convert temperature to C ... ')\n #out_file = deepcopy(xr.open_dataset(dst_data_global_step))\n out_file['2t_C'] = out_file['2t'] - 273.15\n out_file['2t_C'].attrs['long_name'] = '2 metre temperature'\n out_file['2t_C'].attrs['units'] = 'C'\n out_file['2t_C'].attrs['standard_name'] = \"air_temperature\"\n out_file = out_file.rename({'2t': '2t_K'})\n #out_file.to_netcdf(dst_data_global_step)\n logging.info(' ------> Convert temperature to C ... DONE')\n else:\n raise NotImplementedError\n\n if 'tp' in var_in.tolist() and source_standards['source_precipitation_is_cumulated'] is True:\n logging.info(' ------> Decumulate precipitation ... ')\n #out_file = deepcopy(xr.open_dataset(dst_data_global_step))\n #os.remove(dst_data_global_step)\n temp = np.diff(out_file['tp'].values, n=1, axis=0, prepend=0)\n out_file['tp'][np.arange(2,out_file['tp'].values.shape[0],2),:,:].values = temp[np.arange(2,out_file['tp'].values.shape[0],2),:,:]\n out_file['tp'].values = out_file['tp'].values/3\n out_file['tp'].attrs['long_name'] = 'hourly precipitation depth'\n out_file['tp'].attrs['units'] = 'mm'\n out_file['tp'].attrs['standard_name'] = \"precipitation\"\n #out_file.to_netcdf(dst_data_global_step)\n logging.info(' ------> Decumulate precipitation ... DONE')\n\n if '10u' in var_in.tolist() and source_standards['source_wind_separate_components'] is True:\n logging.info(' ------> Combine wind component ... ')\n #out_file = deepcopy(xr.open_dataset(dst_data_global_step))\n #os.remove(dst_data_global_step)\n out_file['10wind'] = np.sqrt(out_file['10u']**2 + out_file['10v']**2)\n out_file['10wind'].attrs['long_name'] = '10 m wind'\n out_file['10wind'].attrs['units'] = 'm s**-1'\n out_file['10wind'].attrs['standard_name'] = \"wind\"\n #out_file.to_netcdf(dst_data_global_step)\n logging.info(' ------> Combine wind component ... DONE')\n\n # out_file = deepcopy(xr.open_dataset(dst_data_global_step))\n # os.remove(dst_data_global_step)\n\n # Check if file has \"heigth\" dimension and remove it\n try:\n out_file = out_file.squeeze(dim=\"height\", drop=True)\n out_file = out_file.squeeze(dim=\"height_2\", drop=True)\n logging.info(' ------> Remove height dimensions ... ')\n except:\n pass\n\n # Reindex time axis by padding last available map over the time range\n out_file=out_file.reindex(time=date_range, method='nearest')\n out_file.to_netcdf(dst_data_global_step)\n\n if os.path.exists(tmp_data_global_step_cat):\n os.remove(tmp_data_global_step_cat)\n if os.path.exists(tmp_data_global_step_seltimestep):\n os.remove(tmp_data_global_step_seltimestep)\n if os.path.exists(tmp_data_global_step_convert):\n os.remove(tmp_data_global_step_convert)\n\n logging.info(' ------> Merge, convert and project data ... DONE')\n else:\n logging.info(' ------> Merge, convert and project data ... SKIPPED. Data already merged.')\n\n logging.info(' ------> Mask data over domain ... ')\n if not os.path.exists(dst_data_domain_step):\n if bbox_cdo is not None:\n cdo.sellonlatbox(bbox_cdo, input=dst_data_global_step, output=dst_data_domain_step)\n logging.info(' ------> Mask data over domain ... DONE')\n else:\n logging.info(' ------> Mask data over domain ... SKIPPED. Domain bounding box not defined.')\n else:\n logging.info(' ------> Mask data over domain ... SKIPPED. Data already masked.')\n\n logging.info(' -----> Type ' + src_key_step + ' ... DONE')\n\n logging.info(' ----> Dumping data ... DONE')\n# -------------------------------------------------------------------------------------\n\n\n# -------------------------------------------------------------------------------------\n# Method to drop data\ndef select_time_steps(info_file, id_start=2, id_end=None, id_period=2):\n\n if id_end is None:\n id_end = int(info_file[-1].split()[0])\n\n list_vars = []\n for info_row in info_file[:-1]:\n info_list = info_row.split()\n\n info_id = int(info_list[0])\n info_var = info_list[12]\n\n if info_id >= 0:\n list_vars.append(info_var)\n\n var_box = list(set(list_vars))\n\n ids_info = [str(id_start), str(id_end), str(id_period)]\n ids_box = '/'.join(ids_info)\n\n return var_box, ids_box\n# -------------------------------------------------------------------------------------\n\n\n# -------------------------------------------------------------------------------------\n# Method to create a tmp name\ndef create_filename_tmp(prefix='gfs_tmp_', suffix='.grib2', folder=None):\n\n if folder is None:\n folder = '/tmp'\n\n with tempfile.NamedTemporaryFile(dir=folder, prefix=prefix, suffix=suffix, delete=False) as tmp:\n temp_file_name = tmp.name\n return temp_file_name\n# -------------------------------------------------------------------------------------\n\n\n# -------------------------------------------------------------------------------------\n# Method to retrieve and store data (multiprocess)\ndef retrieve_data_source_mp(src_data, dst_data, flag_updating=False, process_n=20, process_max=None, limit=9999):\n\n logging.info(' ----> Downloading data in multiprocessing mode ... ')\n\n if process_max is None:\n process_max = cpu_count() - 1\n if process_n > process_max:\n logging.warning(' ----> Maximum of recommended processes must be less then ' + str(process_max))\n logging.warning(' ----> Set number of process from ' + str(process_n) + ' to ' + str(process_max))\n process_n = process_max\n\n data_list = []\n data_check = []\n for (src_data_key, src_data_list), (dst_data_key, dst_data_list) in zip(src_data.items(), dst_data.items()):\n for src_step_url, dst_step_path in zip(src_data_list, dst_data_list):\n dst_step_root, dst_step_file = split(dst_step_path)\n make_folder(dst_step_root)\n\n if exists(dst_step_path) and flag_updating:\n flag_updating = True\n elif (not exists(dst_step_path)) and flag_updating:\n flag_updating = True\n elif (not exists(dst_step_path)) and (not flag_updating):\n flag_updating = True\n if flag_updating:\n data_list.append([src_step_url, dst_step_path])\n\n data_check.append([src_step_url, dst_step_path])\n\n if len(data_list)>limit:\n for i in range(0,len(data_list),limit):\n max_available = min(i + limit, len(data_list))\n chunk = data_list[i:i + limit]\n\n with Pool(processes=process_n, maxtasksperchild=1) as process_pool:\n _ = process_pool.map(request_data_source, chunk, chunksize=1)\n process_pool.close()\n process_pool.join()\n\n logging.info(' ----> Wait 60 seconds for next requests ...')\n time.sleep(60)\n if max_available<len(data_list):\n logging.info(' ----> ' + str(int(100*max_available/len(data_list))) + ' % complete...')\n logging.info(' ----> Continue with next chunk of requests...')\n else:\n with Pool(processes=process_n, maxtasksperchild=1) as process_pool:\n _ = process_pool.map(request_data_source, data_list, chunksize=1)\n process_pool.close()\n process_pool.join()\n\n find_data_corrupted(data_check)\n\n logging.info(' ----> Downloading data in multiprocessing mode ... DONE')\n# -------------------------------------------------------------------------------------\n\n\n# ------------------------------------------------------------------------------------\n# Method to find outliers and to retry for downloading data again\ndef find_data_corrupted(data_list, data_perc_min=5, data_size_min=100000):\n\n logging.info(' -----> Checking for corrupted or unavailable data ... ')\n\n data_size = []\n idx_nodata = []\n for dst_id, dst_step_path in enumerate(data_list):\n if os.path.exists(dst_step_path[1]):\n dst_step_size = os.path.getsize(dst_step_path[1])\n else:\n dst_step_size = 0\n idx_nodata.append(dst_id)\n data_size.append(dst_step_size)\n data_size = np.asarray(data_size)\n\n data_p_min = np.percentile(data_size, data_perc_min)\n\n idx_false = np.where(data_size < min([data_size_min, data_p_min]))[0]\n idx_nodata = np.asarray(idx_nodata, int)\n idx_retry = np.unique(np.concatenate((idx_false, idx_nodata), axis=0))\n\n for idx_step in idx_retry:\n data_false = data_list[idx_step]\n\n if os.path.exists(data_false[1]):\n os.remove(data_false[1])\n\n logging.info(' ------> Downloading data ' + split(data_false[1])[1] + ' ... ')\n request_data_source(data_false)\n logging.info(' ------> Downloading data ' + split(data_false[1])[1] + ' ... DONE')\n\n logging.info(' -----> Checking for corrupted or unavailable data ... DONE')\n# ------------------------------------------------------------------------------------\n\n\n# -------------------------------------------------------------------------------------\n# Method to request data using a source url and a destination filename\ndef request_data_source(data_list):\n logging.info(' :: Http request for downloading: ' + data_list[0] + ' ... ')\n logging.info(' :: Outcome data will be dumped in: ' + split(data_list[1])[1] + ' ... ')\n\n try:\n urllib.request.urlretrieve(data_list[0], filename=data_list[1])\n logging.info(' :: Outcome data will be dumped in: ' + split(data_list[1])[1] + ' ... DONE')\n logging.info(' :: Http request for downloading: ' + data_list[0] + ' ... DONE')\n return True\n except IOError:\n logging.warning(' :: Outcome data will be dumped in: ' + split(data_list[1])[1] + ' ... FAILED')\n logging.error(' :: Http request for downloading: ' + data_list[0] + ' ... FAILED. IO error.')\n raise IOError(' :: Http request for downloading: ' + data_list[0] + ' ... FAILED. Data Not available on the server.')\n except ConnectionResetError:\n logging.warning(' :: Outcome data will be dumped in: ' + split(data_list[1])[1] + ' ... FAILED')\n logging.error(' :: Http request for downloading: ' + data_list[0] + ' ... FAILED. Connection Reset error')\n raise ConnectionResetError(' :: Http request for downloading: ' + data_list[0] + ' ... FAILED. Connection Reset error')\n except ConnectionAbortedError:\n logging.warning(' :: Outcome data will be dumped in: ' + split(data_list[1])[1] + ' ... FAILED')\n logging.error(' :: Http request for downloading: ' + data_list[0] + ' ... FAILED. Connetction Aborted error.')\n raise ConnectionAbortedError(' :: Http request for downloading: ' + data_list[0] + ' ... FAILED. Connetction Aborted error.')\n# -------------------------------------------------------------------------------------\n\n\n# -------------------------------------------------------------------------------------\n# Method to retrieve and store data (sequential)\ndef retrieve_data_source_seq(src_data, dst_data, flag_updating=False, limit=9999):\n\n logging.info(' ----> Downloading data in sequential mode ... ')\n\n data_list = []\n data_check = []\n hit_count = 0\n for (src_data_key, src_data_list), (dst_data_key, dst_data_list) in zip(src_data.items(), dst_data.items()):\n\n logging.info(' -----> DataType: ' + src_data_key + ' ... ')\n\n for src_step_url, dst_step_path in zip(src_data_list, dst_data_list):\n\n dst_step_root, dst_step_file = split(dst_step_path)\n make_folder(dst_step_root)\n\n logging.info(' ------> Save data in file: ' + str(dst_step_file) + ' ... ')\n if exists(dst_step_path) and flag_updating:\n flag_updating = True\n elif (not exists(dst_step_path)) and flag_updating:\n flag_updating = True\n elif (not exists(dst_step_path)) and (not flag_updating):\n flag_updating = True\n\n if flag_updating:\n request_data_source([src_step_url, dst_step_path])\n hit_count += 1\n data_list.append([src_step_url, dst_step_path])\n logging.info(' -------> Save data in file: ' + str(dst_step_file) + ' ... DONE')\n if hit_count == limit:\n logging.info(' ----> Wait 60 seconds for next requests ...')\n time.sleep(60)\n hit_count = 0\n logging.info(' ----> Continue with next chunk of requests...')\n else:\n logging.info(' ------> Save data in file: ' + str(dst_step_file) +\n ' ... SKIPPED. File saved previously')\n\n data_check.append([src_step_url, dst_step_path])\n\n logging.info(' -----> DataType: ' + src_data_key + ' ... DONE')\n\n find_data_corrupted(data_check)\n\n logging.info(' ----> Downloading data in sequential mode ... DONE')\n# -------------------------------------------------------------------------------------\n\n\n# -------------------------------------------------------------------------------------\n# Method to create data outcome list\ndef set_data_outcome(time_run, ens_member_num, data_def, geo_def, ancillary_def, tags_template,\n type_data=None, flag_updating=True):\n\n if type_data is None:\n type_data = [\"surface\"]\n\n folder_list = data_def['folder']\n filename_list = data_def['filename']\n\n lon_right = geo_def['lon_right']\n lon_left = geo_def['lon_left']\n lat_top = geo_def['lat_top']\n lat_bottom = geo_def['lat_bottom']\n\n domain = ancillary_def['domain']\n ens_member = str(ens_member_num).zfill(2)\n\n hour_run = time_run.hour\n datetime_run = time_run.to_pydatetime()\n file_ws = {}\n for folder_raw, filename_raw, type_step in zip(folder_list, filename_list, type_data):\n file_list = []\n\n tags_values_step = {\"domain\": domain,\n \"outcome_sub_path_time\": datetime_run, \"outcome_datetime\": datetime_run,\n \"run_hour\": hour_run, \"run_step\": 0,\n \"run_datetime\": datetime_run,\n \"run_lon_right\": str(lon_right),\n \"run_lon_left\": str(lon_left),\n \"run_lat_bottom\": str(lat_bottom),\n \"run_lat_top\": str(lat_top),\n \"ens_member\" : ens_member}\n\n folder_step = fill_tags2string(folder_raw, tags_template, tags_values_step)\n filename_step = fill_tags2string(filename_raw, tags_template, tags_values_step)\n\n path_step = join(folder_step, filename_step)\n\n if flag_updating:\n if os.path.exists(path_step):\n os.remove(path_step)\n\n if not os.path.exists(folder_step):\n make_folder(folder_step)\n\n file_list.append(path_step)\n\n file_ws[type_step] = file_list\n\n return file_ws\n\n# -------------------------------------------------------------------------------------\n\n\n# -------------------------------------------------------------------------------------\n# Method to create data ancillary list\ndef set_data_ancillary(time_run, time_range, ens_member_num, data_def, geo_def, ancillary_def, tags_template,\n type_data=None, anl_include=False):\n\n if type_data is None:\n type_data = [\"surface\"]\n\n folder_list = data_def['folder']\n filename_list = data_def['filename']\n\n lon_right = geo_def['lon_right']\n lon_left = geo_def['lon_left']\n lat_top = geo_def['lat_top']\n lat_bottom = geo_def['lat_bottom']\n\n domain = ancillary_def['domain']\n ens_member = str(ens_member_num).zfill(2)\n\n hour_run = time_run.hour\n datetime_run = time_run.to_pydatetime()\n file_ws = {}\n for folder_raw, filename_raw, type_step in zip(folder_list, filename_list, type_data):\n file_list = []\n for time_id, time_step in enumerate(time_range):\n\n if not anl_include:\n time_id = time_id + 1\n\n datetime_step = time_step.to_pydatetime()\n tags_values_step = {\"domain\": domain,\n \"ancillary_sub_path_time\": datetime_run, \"ancillary_datetime\": datetime_step,\n \"run_hour\": hour_run, \"run_step\": time_id,\n \"run_datetime\": datetime_run,\n \"run_lon_right\": str(lon_right),\n \"run_lon_left\": str(lon_left),\n \"run_lat_bottom\": str(lat_bottom),\n \"run_lat_top\": str(lat_top),\n \"ens_member\": ens_member}\n\n folder_step = fill_tags2string(folder_raw, tags_template, tags_values_step)\n filename_step = fill_tags2string(filename_raw, tags_template, tags_values_step)\n\n path_step = join(folder_step, filename_step)\n\n file_list.append(path_step)\n\n file_ws[type_step] = file_list\n\n return file_ws\n\n# -------------------------------------------------------------------------------------\n\n\n# -------------------------------------------------------------------------------------\n# Method to create data source list\ndef set_data_source(time_run, time_range, ens_member_num, data_def, geo_def, ancillary_def, tags_template,\n type_data=None, anl_include=False):\n\n if type_data is None:\n type_data = [\"surface\"]\n\n url_root_list = data_def['url_root']\n url_file_list = data_def['url_file']\n url_lev_list = data_def['url_lev']\n url_vars_list = data_def['url_vars']\n url_bbox_list = data_def['url_bbox']\n url_loc_list = data_def['url_loc']\n\n lon_right = geo_def['lon_right']\n lon_left = geo_def['lon_left']\n lat_top = geo_def['lat_top']\n lat_bottom = geo_def['lat_bottom']\n\n domain = ancillary_def['domain']\n ens_member = str(ens_member_num).zfill(2)\n\n frc_steps = (time_range - time_run).total_seconds()/3600\n\n hour_run = time_run.hour\n datetime_run = time_run.to_pydatetime()\n url_ws = {}\n for url_root_raw, url_file_raw, url_lev_raw, url_vars_raw, url_bbox_raw, url_loc_raw, type_step in zip(\n url_root_list, url_file_list, url_lev_list, url_vars_list, url_bbox_list, url_loc_list, type_data):\n\n if url_bbox_raw is None:\n url_bbox_raw = ''\n\n url_list = []\n for time_id, time_step in zip(frc_steps, time_range):\n\n datetime_step = time_step.to_pydatetime()\n tags_values_step = {\"domain\": domain,\n \"outcome_sub_path_time\": datetime_run, \"outcome_datetime\": datetime_step,\n \"run_hour\": hour_run, \"run_step\": int(time_id),\n \"run_datetime\": datetime_run,\n \"run_lon_right\": str(lon_right),\n \"run_lon_left\": str(lon_left),\n \"run_lat_bottom\": str(lat_bottom),\n \"run_lat_top\": str(lat_top),\n \"ens_member\": ens_member}\n\n url_root_step = fill_tags2string(url_root_raw, tags_template, tags_values_step)\n url_file_step = fill_tags2string(url_file_raw, tags_template, tags_values_step)\n url_lev_step = fill_tags2string(url_lev_raw, tags_template, tags_values_step)\n url_vars_step = fill_tags2string(url_vars_raw, tags_template, tags_values_step)\n url_bbox_step = fill_tags2string(url_bbox_raw, tags_template, tags_values_step)\n url_loc_step = fill_tags2string(url_loc_raw, tags_template, tags_values_step)\n\n url_step = url_root_step + url_file_step + url_lev_step + url_vars_step + url_bbox_step + url_loc_step\n\n url_list.append(url_step)\n\n url_ws[type_step] = url_list\n\n return url_ws\n# -------------------------------------------------------------------------------------\n\n\n# -------------------------------------------------------------------------------------\n# Method to add time in a unfilled string (path or filename)\ndef fill_tags2string(string_raw, tags_format=None, tags_filling=None):\n\n apply_tags = False\n if string_raw is not None:\n for tag in list(tags_format.keys()):\n if tag in string_raw:\n apply_tags = True\n break\n\n if apply_tags:\n\n tags_format_tmp = deepcopy(tags_format)\n for tag_key, tag_value in tags_format.items():\n tag_key_tmp = '{' + tag_key + '}'\n if tag_value is not None:\n if tag_key_tmp in string_raw:\n string_filled = string_raw.replace(tag_key_tmp, tag_value)\n string_raw = string_filled\n else:\n tags_format_tmp.pop(tag_key, None)\n\n for tag_format_name, tag_format_value in list(tags_format_tmp.items()):\n\n if tag_format_name in list(tags_filling.keys()):\n tag_filling_value = tags_filling[tag_format_name]\n if tag_filling_value is not None:\n\n if isinstance(tag_filling_value, datetime):\n tag_filling_value = tag_filling_value.strftime(tag_format_value)\n\n if isinstance(tag_filling_value, (float, int)):\n tag_filling_value = tag_format_value.format(tag_filling_value)\n\n string_filled = string_filled.replace(tag_format_value, tag_filling_value)\n\n string_filled = string_filled.replace('//', '/')\n return string_filled\n else:\n return string_raw\n# -------------------------------------------------------------------------------------\n\n\n# -------------------------------------------------------------------------------------\n# Method to define data time range\ndef set_data_time(time_step, time_settings):\n\n time_period_obs = time_settings['time_observed_period']\n time_period_for = time_settings['time_forecast_period']\n time_freq_obs = time_settings['time_observed_frequency']\n time_freq_for = time_settings['time_forecast_frequency']\n\n time_step_obs = time_step\n time_range_obs = pd.date_range(end=time_step_obs, periods=time_period_obs, freq=time_freq_obs)\n\n time_step_for = pd.date_range([time_step][0], periods=2, freq=time_freq_for)[-1]\n time_range_for = pd.date_range(start=time_step_for, periods=time_period_for, freq=time_freq_for)\n\n time_range_data = time_range_obs.union(time_range_for)\n\n return time_range_data\n# -------------------------------------------------------------------------------------\n\n\n# -------------------------------------------------------------------------------------\n# Method to check time validity\ndef check_time_limit(time_alg, time_name='time_step', time_limit_period='9D', time_round='D'):\n time_day = pd.Timestamp.today()\n time_limit_upper = time_day.floor(time_round)\n time_limit_lower = pd.date_range(end=time_limit_upper, periods=2, freq=time_limit_period)[0]\n\n if time_alg < time_limit_lower:\n logging.error(' ===> ' + time_name + ' is not available on source database! It is less then DB time_from')\n raise IOError(time_name + ' is not correctly defined! Check your settings or algorithm args!')\n elif time_alg > time_limit_upper:\n logging.error(' ===> ' + time_name + ' is not available on source database! It is greater then DB time_to')\n raise IOError(time_name + ' is not correctly defined! Check your settings or algorithm args!')\n else:\n pass\n# -------------------------------------------------------------------------------------\n\n\n# -------------------------------------------------------------------------------------\n# Method to define run time range\ndef set_run_time(time_alg, time_settings):\n\n time_set = time_settings['time_now']\n time_freq = time_settings['time_frequency']\n time_round = time_settings['time_rounding']\n time_period = time_settings['time_period']\n\n if time_period < 1:\n time_period = 1\n logging.warning(' ===> TimePeriod must be greater then zero! TimePeriod set to 1.')\n\n if time_alg and time_set:\n time_now = time_alg\n elif time_alg is None and time_set:\n time_now = time_set\n elif time_alg and time_set is None:\n time_now = time_alg\n else:\n logging.error(' ===> TimeNow is not correctly set!')\n raise IOError('TimeNow is undefined! Check your settings or algorithm args!')\n\n time_now_raw = pd.Timestamp(time_now)\n time_now_round = time_now_raw.floor(time_round)\n\n if time_period > 0:\n time_range = pd.date_range(end=time_now_round, periods=time_period, freq=time_freq)\n else:\n logging.warning(' ===> TimePeriod must be greater then 0. TimePeriod is set automatically to 1')\n time_range = pd.DatetimeIndex([time_now_round], freq=time_freq)\n\n check_time_limit(time_now_round, time_name='time_now', time_round=time_round)\n check_time_limit(time_range[0], time_name='time_run_from', time_round='H')\n if time_period > 1:\n check_time_limit(time_range[1], time_name='time_run_to', time_round='H')\n else:\n check_time_limit(time_range[0], time_name='time_run_to', time_round='H')\n return time_now_round, time_range\n\n# -------------------------------------------------------------------------------------\n\n\n# -------------------------------------------------------------------------------------\n# Method to make folder\ndef make_folder(path_folder):\n if not exists(path_folder):\n makedirs(path_folder)\n# -------------------------------------------------------------------------------------\n\n\n# -------------------------------------------------------------------------------------\n# Method to read file json\ndef read_file_json(file_name):\n\n env_ws = {}\n for env_item, env_value in os.environ.items():\n env_ws[env_item] = env_value\n\n with open(file_name, \"r\") as file_handle:\n json_block = []\n for file_row in file_handle:\n\n for env_key, env_value in env_ws.items():\n env_tag = '$' + env_key\n if env_tag in file_row:\n env_value = env_value.strip(\"'\\\\'\")\n file_row = file_row.replace(env_tag, env_value)\n file_row = file_row.replace('//', '/')\n\n # Add the line to our JSON block\n json_block.append(file_row)\n\n # Check whether we closed our JSON block\n if file_row.startswith('}'):\n # Do something with the JSON dictionary\n json_dict = json.loads(''.join(json_block))\n # Start a new block\n json_block = []\n\n return json_dict\n# -------------------------------------------------------------------------------------\n\n# -------------------------------------------------------------------------------------\n# Method to get script argument(s)\ndef get_args():\n parser_handle = ArgumentParser()\n parser_handle.add_argument('-settings_file', action=\"store\", dest=\"alg_settings\")\n parser_handle.add_argument('-time', action=\"store\", dest=\"alg_time\")\n parser_values = parser_handle.parse_args()\n\n if parser_values.alg_settings:\n alg_settings = parser_values.alg_settings\n else:\n alg_settings = 'configuration.json'\n\n if parser_values.alg_time:\n alg_time = parser_values.alg_time\n else:\n alg_time = None\n\n return alg_settings, alg_time\n# -------------------------------------------------------------------------------------\n\n# -------------------------------------------------------------------------------------\n# Method to set logging information\ndef set_logging(logger_file='log.txt', logger_format=None):\n\n if logger_format is None:\n logger_format = '%(asctime)s %(name)-12s %(levelname)-8s ' \\\n '%(filename)s:[%(lineno)-6s - %(funcName)20s()] %(message)s'\n\n # Remove old logging file\n if os.path.exists(logger_file):\n os.remove(logger_file)\n\n # Set level of root debugger\n logging.root.setLevel(logging.DEBUG)\n\n # Open logging basic configuration\n logging.basicConfig(level=logging.DEBUG, format=logger_format, filename=logger_file, filemode='w')\n\n # Set logger handle\n logger_handle_1 = logging.FileHandler(logger_file, 'w')\n logger_handle_2 = logging.StreamHandler()\n # Set logger level\n logger_handle_1.setLevel(logging.DEBUG)\n logger_handle_2.setLevel(logging.DEBUG)\n # Set logger formatter\n logger_formatter = logging.Formatter(logger_format)\n logger_handle_1.setFormatter(logger_formatter)\n logger_handle_2.setFormatter(logger_formatter)\n\n # Add handle to logging\n logging.getLogger('').addHandler(logger_handle_1)\n logging.getLogger('').addHandler(logger_handle_2)\n\n# -------------------------------------------------------------------------------------\n\n# ----------------------------------------------------------------------------\n# Call script from external library\nif __name__ == \"__main__\":\n main()\n# ----------------------------------------------------------------------------\n"
] | [
[
"pandas.DatetimeIndex",
"numpy.unique",
"pandas.date_range",
"numpy.diff",
"pandas.Timestamp.today",
"numpy.asarray",
"pandas.Timedelta",
"numpy.arange",
"numpy.sqrt",
"numpy.concatenate",
"pandas.Timestamp",
"numpy.percentile"
]
] |
YibinXie/Pose_Estimation | [
"5849140bf842bf3aeaad75827f5e7b7f2999c9ee"
] | [
"lib/models/cpm.py"
] | [
"import torch.nn as nn\nimport torch.nn.functional as F\nimport torch\n\n\nclass CPM(nn.Module):\n def __init__(self, k):\n super(CPM, self).__init__()\n self.k = k\n self.pool_center = nn.AvgPool2d(kernel_size=9, stride=8, padding=1)\n self.conv1_stage1 = nn.Conv2d(3, 128, kernel_size=9, padding=4)\n self.pool1_stage1 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.conv2_stage1 = nn.Conv2d(128, 128, kernel_size=9, padding=4)\n self.pool2_stage1 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.conv3_stage1 = nn.Conv2d(128, 128, kernel_size=9, padding=4)\n self.pool3_stage1 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.conv4_stage1 = nn.Conv2d(128, 32, kernel_size=5, padding=2)\n self.conv5_stage1 = nn.Conv2d(32, 512, kernel_size=9, padding=4)\n self.conv6_stage1 = nn.Conv2d(512, 512, kernel_size=1)\n self.conv7_stage1 = nn.Conv2d(512, self.k + 1, kernel_size=1)\n\n self.conv1_stage2 = nn.Conv2d(3, 128, kernel_size=9, padding=4)\n self.pool1_stage2 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.conv2_stage2 = nn.Conv2d(128, 128, kernel_size=9, padding=4)\n self.pool2_stage2 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.conv3_stage2 = nn.Conv2d(128, 128, kernel_size=9, padding=4)\n self.pool3_stage2 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.conv4_stage2 = nn.Conv2d(128, 32, kernel_size=5, padding=2)\n\n self.Mconv1_stage2 = nn.Conv2d(32 + self.k + 2, 128, kernel_size=11, padding=5)\n self.Mconv2_stage2 = nn.Conv2d(128, 128, kernel_size=11, padding=5)\n self.Mconv3_stage2 = nn.Conv2d(128, 128, kernel_size=11, padding=5)\n self.Mconv4_stage2 = nn.Conv2d(128, 128, kernel_size=1, padding=0)\n self.Mconv5_stage2 = nn.Conv2d(128, self.k + 1, kernel_size=1, padding=0)\n\n self.conv1_stage3 = nn.Conv2d(128, 32, kernel_size=5, padding=2)\n\n self.Mconv1_stage3 = nn.Conv2d(32 + self.k + 2, 128, kernel_size=11, padding=5)\n self.Mconv2_stage3 = nn.Conv2d(128, 128, kernel_size=11, padding=5)\n self.Mconv3_stage3 = nn.Conv2d(128, 128, kernel_size=11, padding=5)\n self.Mconv4_stage3 = nn.Conv2d(128, 128, kernel_size=1, padding=0)\n self.Mconv5_stage3 = nn.Conv2d(128, self.k + 1, kernel_size=1, padding=0)\n\n self.conv1_stage4 = nn.Conv2d(128, 32, kernel_size=5, padding=2)\n\n self.Mconv1_stage4 = nn.Conv2d(32 + self.k + 2, 128, kernel_size=11, padding=5)\n self.Mconv2_stage4 = nn.Conv2d(128, 128, kernel_size=11, padding=5)\n self.Mconv3_stage4 = nn.Conv2d(128, 128, kernel_size=11, padding=5)\n self.Mconv4_stage4 = nn.Conv2d(128, 128, kernel_size=1, padding=0)\n self.Mconv5_stage4 = nn.Conv2d(128, self.k + 1, kernel_size=1, padding=0)\n\n self.conv1_stage5 = nn.Conv2d(128, 32, kernel_size=5, padding=2)\n\n self.Mconv1_stage5 = nn.Conv2d(32 + self.k + 2, 128, kernel_size=11, padding=5)\n self.Mconv2_stage5 = nn.Conv2d(128, 128, kernel_size=11, padding=5)\n self.Mconv3_stage5 = nn.Conv2d(128, 128, kernel_size=11, padding=5)\n self.Mconv4_stage5 = nn.Conv2d(128, 128, kernel_size=1, padding=0)\n self.Mconv5_stage5 = nn.Conv2d(128, self.k + 1, kernel_size=1, padding=0)\n\n self.conv1_stage6 = nn.Conv2d(128, 32, kernel_size=5, padding=2)\n\n self.Mconv1_stage6 = nn.Conv2d(32 + self.k + 2, 128, kernel_size=11, padding=5)\n self.Mconv2_stage6 = nn.Conv2d(128, 128, kernel_size=11, padding=5)\n self.Mconv3_stage6 = nn.Conv2d(128, 128, kernel_size=11, padding=5)\n self.Mconv4_stage6 = nn.Conv2d(128, 128, kernel_size=1, padding=0)\n self.Mconv5_stage6 = nn.Conv2d(128, self.k + 1, kernel_size=1, padding=0)\n\n def _stage1(self, image):\n x = self.pool1_stage1(F.relu(self.conv1_stage1(image)))\n x = self.pool2_stage1(F.relu(self.conv2_stage1(x)))\n x = self.pool3_stage1(F.relu(self.conv3_stage1(x)))\n x = F.relu(self.conv4_stage1(x))\n x = F.relu(self.conv5_stage1(x))\n x = F.relu(self.conv6_stage1(x))\n x = self.conv7_stage1(x)\n\n return x\n\n def _middle(self, image):\n x = self.pool1_stage2(F.relu(self.conv1_stage2(image)))\n x = self.pool2_stage2(F.relu(self.conv2_stage2(x)))\n x = self.pool3_stage2(F.relu(self.conv3_stage2(x)))\n\n return x\n\n def _stage2(self, pool3_stage2_map, conv7_stage1_map, pool_center_map):\n x = F.relu(self.conv4_stage2(pool3_stage2_map))\n x = torch.cat([x, conv7_stage1_map, pool_center_map], dim=1)\n x = F.relu(self.Mconv1_stage2(x))\n x = F.relu(self.Mconv2_stage2(x))\n x = F.relu(self.Mconv3_stage2(x))\n x = F.relu(self.Mconv4_stage2(x))\n x = self.Mconv5_stage2(x)\n\n return x\n\n def _stage3(self, pool3_stage2_map, Mconv5_stage2_map, pool_center_map):\n x = F.relu(self.conv1_stage3(pool3_stage2_map))\n x = torch.cat([x, Mconv5_stage2_map, pool_center_map], dim=1)\n x = F.relu(self.Mconv1_stage3(x))\n x = F.relu(self.Mconv2_stage3(x))\n x = F.relu(self.Mconv3_stage3(x))\n x = F.relu(self.Mconv4_stage3(x))\n x = self.Mconv5_stage3(x)\n\n return x\n\n def _stage4(self, pool3_stage2_map, Mconv5_stage3_map, pool_center_map):\n x = F.relu(self.conv1_stage4(pool3_stage2_map))\n x = torch.cat([x, Mconv5_stage3_map, pool_center_map], dim=1)\n x = F.relu(self.Mconv1_stage4(x))\n x = F.relu(self.Mconv2_stage4(x))\n x = F.relu(self.Mconv3_stage4(x))\n x = F.relu(self.Mconv4_stage4(x))\n x = self.Mconv5_stage4(x)\n\n return x\n\n def _stage5(self, pool3_stage2_map, Mconv5_stage4_map, pool_center_map):\n x = F.relu(self.conv1_stage5(pool3_stage2_map))\n x = torch.cat([x, Mconv5_stage4_map, pool_center_map], dim=1)\n x = F.relu(self.Mconv1_stage5(x))\n x = F.relu(self.Mconv2_stage5(x))\n x = F.relu(self.Mconv3_stage5(x))\n x = F.relu(self.Mconv4_stage5(x))\n x = self.Mconv5_stage5(x)\n\n return x\n\n def _stage6(self, pool3_stage2_map, Mconv5_stage5_map, pool_center_map):\n x = F.relu(self.conv1_stage6(pool3_stage2_map))\n x = torch.cat([x, Mconv5_stage5_map, pool_center_map], dim=1)\n x = F.relu(self.Mconv1_stage6(x))\n x = F.relu(self.Mconv2_stage6(x))\n x = F.relu(self.Mconv3_stage6(x))\n x = F.relu(self.Mconv4_stage6(x))\n x = self.Mconv5_stage6(x)\n\n return x\n\n def forward(self, image, center_map):\n pool_center_map = self.pool_center(center_map)\n\n conv7_stage1_map = self._stage1(image)\n\n pool3_stage2_map = self._middle(image)\n\n Mconv5_stage2_map = self._stage2(pool3_stage2_map, conv7_stage1_map,\n pool_center_map)\n Mconv5_stage3_map = self._stage3(pool3_stage2_map, Mconv5_stage2_map,\n pool_center_map)\n Mconv5_stage4_map = self._stage4(pool3_stage2_map, Mconv5_stage3_map,\n pool_center_map)\n Mconv5_stage5_map = self._stage5(pool3_stage2_map, Mconv5_stage4_map,\n pool_center_map)\n Mconv5_stage6_map = self._stage6(pool3_stage2_map, Mconv5_stage5_map,\n pool_center_map)\n\n return conv7_stage1_map, Mconv5_stage2_map, Mconv5_stage3_map, Mconv5_stage4_map, Mconv5_stage5_map, Mconv5_stage6_map\n\n\ndef get_pose_net(cfg, is_train, **kwargs):\n model = CPM(16)\n\n return model\n\n\nif __name__ == '__main__':\n from torchsummary import summary\n\n model = get_pose_net('', True).cuda()\n summary(model, (3, 256, 256))"
] | [
[
"torch.nn.MaxPool2d",
"torch.nn.Conv2d",
"torch.cat",
"torch.nn.AvgPool2d"
]
] |
AntixK/Neural-Blocks | [
"018a44bbb703fc848234b95a3e604576bd9df88f"
] | [
"blocks/convnormpool.py"
] | [
"import torch.nn as nn\nfrom NeuralBlocks.blocks.convnorm import ConvNorm\n\nclass ConvNormPool(nn.Module):\n \"\"\"\n A simply block consisting of a convolution layer,\n a normalization layer and a pooling\n layer. For example, this is the first block in the\n ResNet architecture.\n \"\"\"\n\n def __init__(self, in_channels, out_channels, conv_kernel_size=3,\n conv_stride=1, conv_padding=1, conv_bias=False, norm='BN',\n pool_type='max',pool_kernel_size=2, pool_stride=1,pool_padding=0):\n super(ConvNormPool, self).__init__()\n\n if pool_type not in ['max', 'avg']:\n raise ValueError(\"pool_type must be either 'max' or 'avg'.\")\n\n self.conv_norm = ConvNorm(in_channels, out_channels, norm=norm,\n kernel_size=conv_kernel_size, stride= conv_stride,\n padding=conv_padding, bias= conv_bias)\n\n if pool_type is 'max':\n self.maxpool = nn.MaxPool2d(kernel_size=pool_kernel_size,\n stride=pool_stride, padding=pool_padding)\n else:\n self.maxpool = nn.AvgPool2d(kernel_size=pool_kernel_size,\n stride=pool_stride, padding=pool_padding)\n\n\n def forward(self, input):\n x = self.conv_norm(input)\n x = self.maxpool(x)\n return x\n"
] | [
[
"torch.nn.MaxPool2d",
"torch.nn.AvgPool2d"
]
] |
seikurou/LearningByCheating | [
"5e61f8624d79204b367479fab790b23d3af08b57"
] | [
"bird_view/utils/map_utils.py"
] | [
"# Source: https://github.com/carla-simulator/carla\n\n\nimport os\nimport datetime\nimport weakref\nimport math\n\nimport numpy as np\n\nimport carla\n\nfrom carla import TrafficLightState as tls\n\nimport pygame\n\nfrom pygame.locals import KMOD_CTRL\nfrom pygame.locals import KMOD_SHIFT\nfrom pygame.locals import K_COMMA\nfrom pygame.locals import K_DOWN\nfrom pygame.locals import K_ESCAPE\nfrom pygame.locals import K_F1\nfrom pygame.locals import K_LEFT\nfrom pygame.locals import K_PERIOD\nfrom pygame.locals import K_RIGHT\nfrom pygame.locals import K_SLASH\nfrom pygame.locals import K_SPACE\nfrom pygame.locals import K_TAB\nfrom pygame.locals import K_UP\nfrom pygame.locals import K_a\nfrom pygame.locals import K_d\nfrom pygame.locals import K_h\nfrom pygame.locals import K_i\nfrom pygame.locals import K_m\nfrom pygame.locals import K_p\nfrom pygame.locals import K_q\nfrom pygame.locals import K_s\nfrom pygame.locals import K_w\n\n# ==============================================================================\n# -- Constants -----------------------------------------------------------------\n# ==============================================================================\nCOLOR_BUTTER_0 = pygame.Color(252, 233, 79)\nCOLOR_BUTTER_1 = pygame.Color(237, 212, 0)\nCOLOR_BUTTER_2 = pygame.Color(196, 160, 0)\n\nCOLOR_ORANGE_0 = pygame.Color(252, 175, 62)\nCOLOR_ORANGE_1 = pygame.Color(245, 121, 0)\nCOLOR_ORANGE_2 = pygame.Color(209, 92, 0)\n\nCOLOR_CHOCOLATE_0 = pygame.Color(233, 185, 110)\nCOLOR_CHOCOLATE_1 = pygame.Color(193, 125, 17)\nCOLOR_CHOCOLATE_2 = pygame.Color(143, 89, 2)\n\nCOLOR_CHAMELEON_0 = pygame.Color(138, 226, 52)\nCOLOR_CHAMELEON_1 = pygame.Color(115, 210, 22)\nCOLOR_CHAMELEON_2 = pygame.Color(78, 154, 6)\n\nCOLOR_SKY_BLUE_0 = pygame.Color(114, 159, 207)\nCOLOR_SKY_BLUE_1 = pygame.Color(52, 101, 164)\nCOLOR_SKY_BLUE_2 = pygame.Color(32, 74, 135)\n\nCOLOR_PLUM_0 = pygame.Color(173, 127, 168)\nCOLOR_PLUM_1 = pygame.Color(117, 80, 123)\nCOLOR_PLUM_2 = pygame.Color(92, 53, 102)\n\nCOLOR_SCARLET_RED_0 = pygame.Color(239, 41, 41)\nCOLOR_SCARLET_RED_1 = pygame.Color(204, 0, 0)\nCOLOR_SCARLET_RED_2 = pygame.Color(164, 0, 0)\n\nCOLOR_ALUMINIUM_0 = pygame.Color(238, 238, 236)\nCOLOR_ALUMINIUM_1 = pygame.Color(211, 215, 207)\nCOLOR_ALUMINIUM_2 = pygame.Color(186, 189, 182)\nCOLOR_ALUMINIUM_3 = pygame.Color(136, 138, 133)\nCOLOR_ALUMINIUM_4 = pygame.Color(85, 87, 83)\nCOLOR_ALUMINIUM_5 = pygame.Color(46, 52, 54)\n\nCOLOR_WHITE = pygame.Color(255, 255, 255)\nCOLOR_BLACK = pygame.Color(0, 0, 0)\n\nCOLOR_TRAFFIC_RED = pygame.Color(255, 0, 0)\nCOLOR_TRAFFIC_YELLOW = pygame.Color(0, 255, 0)\nCOLOR_TRAFFIC_GREEN = pygame.Color(0, 0, 255)\n\n# Module Defines\nMODULE_WORLD = 'WORLD'\nMODULE_HUD = 'HUD'\nMODULE_INPUT = 'INPUT'\n\nPIXELS_PER_METER = 4\n\nMAP_DEFAULT_SCALE = 0.1\nHERO_DEFAULT_SCALE = 1.0\n\n# (bev-height // 2) + ( ||camera_loc - vehicle_loc|| * PIXELS_PER_METER)\n# ||camera_loc - vehicle_loc|| is the camera's location relative to vehicle; in lbc it is 2 meters\n# (200 // 2) + (2 * 4)\nPIXELS_AHEAD_VEHICLE = 108\n# the center of the final bev image is PIXELS_AHEAD_VEHICLE in ahead the ego vehicle\n\n\ndef get_actor_display_name(actor, truncate=250):\n name = ' '.join(actor.type_id.replace('_', '.').title().split('.')[1:])\n return (name[:truncate - 1] + u'\\u2026') if len(name) > truncate else name\n\n\n# ==============================================================================\n# -- Util -----------------------------------------------------------\n# ==============================================================================\nclass Util(object):\n @staticmethod\n def blits(destination_surface, source_surfaces, rect=None, blend_mode=0):\n for surface in source_surfaces:\n destination_surface.blit(surface[0], surface[1], rect, blend_mode)\n\n @staticmethod\n def length (v):\n return math.sqrt(v.x**2 + v.y**2 + v.z**2)\n\n\n# ==============================================================================\n# -- ModuleManager -------------------------------------------------------------\n# ==============================================================================\nclass ModuleManager(object):\n def __init__(self):\n self.modules = []\n\n def register_module(self, module):\n self.modules.append(module)\n\n def clear_modules(self):\n del self.modules[:]\n\n def tick(self, clock):\n # Update all the modules\n for module in self.modules:\n module.tick(clock)\n\n def render(self, display, snapshot=None):\n display.fill(COLOR_ALUMINIUM_4)\n for module in self.modules:\n module.render(display, snapshot=snapshot)\n\n def get_module(self, name):\n for module in self.modules:\n if module.name == name:\n return module\n\n def start_modules(self):\n for module in self.modules:\n module.start()\n\n\n# ==============================================================================\n# -- FadingText ----------------------------------------------------------------\n# ==============================================================================\n\n\nclass FadingText(object):\n def __init__(self, font, dim, pos):\n self.font = font\n self.dim = dim\n self.pos = pos\n self.seconds_left = 0\n self.surface = pygame.Surface(self.dim)\n\n def set_text(self, text, color=COLOR_WHITE, seconds=2.0):\n text_texture = self.font.render(text, True, color)\n self.surface = pygame.Surface(self.dim)\n self.seconds_left = seconds\n self.surface.fill(COLOR_BLACK)\n self.surface.blit(text_texture, (10, 11))\n\n def tick(self, clock):\n delta_seconds = 1e-3 * clock.get_time()\n self.seconds_left = max(0.0, self.seconds_left - delta_seconds)\n self.surface.set_alpha(500.0 * self.seconds_left)\n\n def render(self, display, snapshot=None):\n display.blit(self.surface, self.pos)\n\n\n# ==============================================================================\n# -- HelpText ------------------------------------------------------------------\n# ==============================================================================\n\n\nclass HelpText(object):\n def __init__(self, font, width, height):\n lines = __doc__.split('\\n')\n self.font = font\n self.dim = (680, len(lines) * 22 + 12)\n self.pos = (0.5 * width - 0.5 * self.dim[0], 0.5 * height - 0.5 * self.dim[1])\n self.seconds_left = 0\n self.surface = pygame.Surface(self.dim)\n self.surface.fill(COLOR_BLACK)\n for n, line in enumerate(lines):\n text_texture = self.font.render(line, True, COLOR_WHITE)\n self.surface.blit(text_texture, (22, n * 22))\n self._render = False\n self.surface.set_alpha(220)\n\n def toggle(self):\n self._render = not self._render\n\n def render(self, display, snapshot=None):\n pass\n if self._render:\n display.blit(self.surface, self.pos)\n\n\n# ==============================================================================\n# -- ModuleHUD -----------------------------------------------------------------\n# ==============================================================================\n\n\nclass ModuleHUD (object):\n\n def __init__(self, name, width, height):\n self.name = name\n self.dim = (width, height)\n self._init_hud_params()\n self._init_data_params()\n\n def start(self):\n pass\n\n def _init_hud_params(self):\n fonts = [x for x in pygame.font.get_fonts() if 'mono' in x]\n default_font = 'ubuntumono'\n mono = default_font if default_font in fonts else fonts[0]\n mono = pygame.font.match_font(mono)\n self._font_mono = pygame.font.Font(mono, 14)\n self._header_font = pygame.font.SysFont('Arial', 14, True)\n # self.help = HelpText(pygame.font.Font(mono, 24), *self.dim)\n self._notifications = FadingText(\n pygame.font.Font(pygame.font.get_default_font(), 20),\n (self.dim[0], 40), (0, self.dim[1] - 40))\n\n def _init_data_params(self):\n self.show_info = True\n self.show_actor_ids = False\n self._info_text = {}\n\n def notification(self, text, seconds=2.0):\n self._notifications.set_text(text, seconds=seconds)\n\n def tick(self, clock):\n self._notifications.tick(clock)\n\n def add_info(self, module_name, info):\n self._info_text[module_name] = info\n\n def render_vehicles_ids(self, vehicle_id_surface, list_actors, world_to_pixel, hero_actor, hero_transform):\n vehicle_id_surface.fill(COLOR_BLACK)\n if self.show_actor_ids:\n vehicle_id_surface.set_alpha(150)\n for actor in list_actors:\n x, y = world_to_pixel(actor[1].location)\n\n angle = 0\n if hero_actor is not None:\n angle = -hero_transform.rotation.yaw - 90\n\n color = COLOR_SKY_BLUE_0\n if int(actor[0].attributes['number_of_wheels']) == 2:\n # color = COLOR_CHOCOLATE_0\n color = COLOR_WHITE\n if actor[0].attributes['role_name'] == 'hero':\n # color = COLOR_CHAMELEON_0\n color = COLOR_WHITE\n\n font_surface = self._header_font.render(str(actor[0].id), True, color)\n rotated_font_surface = pygame.transform.rotate(font_surface, angle)\n rect = rotated_font_surface.get_rect(center=(x, y))\n vehicle_id_surface.blit(rotated_font_surface, rect)\n\n return vehicle_id_surface\n\n def render(self, display, snapshot=None):\n return # Do not render hud\n if self.show_info:\n info_surface = pygame.Surface((240, self.dim[1]))\n info_surface.set_alpha(100)\n display.blit(info_surface, (0, 0))\n v_offset = 4\n bar_h_offset = 100\n bar_width = 106\n i = 0\n for module_name, module_info in self._info_text.items():\n if not module_info:\n continue\n surface = self._header_font.render(module_name, True, COLOR_ALUMINIUM_0).convert_alpha()\n display.blit(surface, (8 + bar_width / 2, 18 * i + v_offset))\n v_offset += 12\n i += 1\n for item in module_info:\n if v_offset + 18 > self.dim[1]:\n break\n if isinstance(item, list):\n if len(item) > 1:\n points = [(x + 8, v_offset + 8 + (1.0 - y) * 30) for x, y in enumerate(item)]\n pygame.draw.lines(display, (255, 136, 0), False, points, 2)\n item = None\n elif isinstance(item, tuple):\n if isinstance(item[1], bool):\n rect = pygame.Rect((bar_h_offset, v_offset + 8), (6, 6))\n pygame.draw.rect(display, COLOR_ALUMINIUM_0, rect, 0 if item[1] else 1)\n else:\n rect_border = pygame.Rect((bar_h_offset, v_offset + 8), (bar_width, 6))\n pygame.draw.rect(display, COLOR_ALUMINIUM_0, rect_border, 1)\n f = (item[1] - item[2]) / (item[3] - item[2])\n if item[2] < 0.0:\n rect = pygame.Rect((bar_h_offset + f * (bar_width - 6), v_offset + 8), (6, 6))\n else:\n rect = pygame.Rect((bar_h_offset, v_offset + 8), (f * bar_width, 6))\n pygame.draw.rect(display, COLOR_ALUMINIUM_0, rect)\n item = item[0]\n if item: # At this point has to be a str.\n surface = self._font_mono.render(item, True, COLOR_ALUMINIUM_0).convert_alpha()\n display.blit(surface, (8, 18 * i + v_offset))\n v_offset += 18\n v_offset += 24\n self._notifications.render(display)\n self.help.render(display)\n\n\n# ==============================================================================\n# -- TrafficLightSurfaces ------------------------------------------------------\n# ==============================================================================\n\n\nclass TrafficLightSurfaces(object):\n \"\"\"Holds the surfaces (scaled and rotated) for painting traffic lights\"\"\"\n\n def __init__(self):\n def make_surface(tl):\n w = 40\n surface = pygame.Surface((w, 3 * w)).convert_alpha()\n surface.fill(COLOR_ALUMINIUM_5 if tl != 'h' else COLOR_ORANGE_2)\n if tl != 'h':\n hw = int(w / 2)\n off = COLOR_ALUMINIUM_4\n red = COLOR_SCARLET_RED_0\n yellow = COLOR_BUTTER_0\n green = COLOR_CHAMELEON_0\n pygame.draw.circle(surface, red if tl == tls.Red else off, (hw, hw), int(0.4 * w))\n pygame.draw.circle(surface, yellow if tl == tls.Yellow else off, (hw, w + hw), int(0.4 * w))\n pygame.draw.circle(surface, green if tl == tls.Green else off, (hw, 2 * w + hw), int(0.4 * w))\n return pygame.transform.smoothscale(surface, (15, 45) if tl != 'h' else (19, 49))\n self._original_surfaces = {\n 'h': make_surface('h'),\n tls.Red: make_surface(tls.Red),\n tls.Yellow: make_surface(tls.Yellow),\n tls.Green: make_surface(tls.Green),\n tls.Off: make_surface(tls.Off),\n tls.Unknown: make_surface(tls.Unknown)\n }\n self.surfaces = dict(self._original_surfaces)\n\n def rotozoom(self, angle, scale):\n for key, surface in self._original_surfaces.items():\n self.surfaces[key] = pygame.transform.rotozoom(surface, angle, scale)\n\n\n# ==============================================================================\n# -- World ---------------------------------------------------------------------\n# ==============================================================================\n\n\nclass MapImage(object):\n def __init__(self, carla_world, carla_map, pixels_per_meter=10):\n self._pixels_per_meter = pixels_per_meter\n self.scale = 1.0\n\n waypoints = carla_map.generate_waypoints(2)\n margin = 50\n max_x = max(waypoints, key=lambda x: x.transform.location.x).transform.location.x + margin\n max_y = max(waypoints, key=lambda x: x.transform.location.y).transform.location.y + margin\n min_x = min(waypoints, key=lambda x: x.transform.location.x).transform.location.x - margin\n min_y = min(waypoints, key=lambda x: x.transform.location.y).transform.location.y - margin\n\n self.width = max(max_x - min_x, max_y - min_y)\n self._world_offset = (min_x, min_y)\n\n width_in_pixels = int(self._pixels_per_meter * self.width)\n\n self.big_map_surface = pygame.Surface((width_in_pixels, width_in_pixels)).convert()\n self.big_lane_surface = pygame.Surface((width_in_pixels, width_in_pixels)).convert()\n self.draw_road_map(\n self.big_map_surface, self.big_lane_surface,\n carla_world, carla_map, self.world_to_pixel, self.world_to_pixel_width)\n self.map_surface = self.big_map_surface\n self.lane_surface = self.big_lane_surface\n\n def draw_road_map(self, map_surface, lane_surface, carla_world, carla_map, world_to_pixel, world_to_pixel_width):\n # map_surface.fill(COLOR_ALUMINIUM_4)\n map_surface.fill(COLOR_BLACK)\n precision = 0.05\n\n def draw_lane_marking(surface, points, solid=True):\n if solid:\n # pygame.draw.lines(surface, COLOR_ORANGE_0, False, points, 2)\n pygame.draw.lines(surface, COLOR_WHITE, False, points, 2)\n else:\n broken_lines = [x for n, x in enumerate(zip(*(iter(points),) * 20)) if n % 3 == 0]\n for line in broken_lines:\n # pygame.draw.lines(surface, COLOR_ORANGE_0, False, line, 2)\n pygame.draw.lines(surface, COLOR_WHITE, False, line, 2)\n\n def draw_arrow(surface, transform, color=COLOR_ALUMINIUM_2):\n transform.rotation.yaw += 180\n forward = transform.get_forward_vector()\n transform.rotation.yaw += 90\n right_dir = transform.get_forward_vector()\n start = transform.location\n end = start + 2.0 * forward\n right = start + 0.8 * forward + 0.4 * right_dir\n left = start + 0.8 * forward - 0.4 * right_dir\n pygame.draw.lines(\n surface, color, False, [\n world_to_pixel(x) for x in [\n start, end]], 4)\n pygame.draw.lines(\n surface, color, False, [\n world_to_pixel(x) for x in [\n left, start, right]], 4)\n\n def draw_stop(surface, font_surface, transform, color=COLOR_ALUMINIUM_2):\n waypoint = carla_map.get_waypoint(transform.location)\n\n angle = -waypoint.transform.rotation.yaw - 90.0\n font_surface = pygame.transform.rotate(font_surface, angle)\n pixel_pos = world_to_pixel(waypoint.transform.location)\n offset = font_surface.get_rect(center=(pixel_pos[0], pixel_pos[1]))\n surface.blit(font_surface, offset)\n\n # Draw line in front of stop\n forward_vector = carla.Location(waypoint.transform.get_forward_vector())\n left_vector = carla.Location(-forward_vector.y, forward_vector.x, forward_vector.z) * waypoint.lane_width/2 * 0.7\n\n line = [(waypoint.transform.location + (forward_vector * 1.5) + (left_vector)),\n (waypoint.transform.location + (forward_vector * 1.5) - (left_vector))]\n \n line_pixel = [world_to_pixel(p) for p in line]\n pygame.draw.lines(surface, color, True, line_pixel, 2)\n\n \n\n def lateral_shift(transform, shift):\n transform.rotation.yaw += 90\n return transform.location + shift * transform.get_forward_vector()\n\n def does_cross_solid_line(waypoint, shift):\n w = carla_map.get_waypoint(lateral_shift(waypoint.transform, shift), project_to_road=False)\n if w is None or w.road_id != waypoint.road_id:\n return True\n else:\n return (w.lane_id * waypoint.lane_id < 0) or w.lane_id == waypoint.lane_id\n\n topology = [x[0] for x in carla_map.get_topology()]\n topology = sorted(topology, key=lambda w: w.transform.location.z)\n \n for waypoint in topology:\n waypoints = [waypoint]\n nxt = waypoint.next(precision)[0]\n while nxt.road_id == waypoint.road_id:\n waypoints.append(nxt)\n nxt = nxt.next(precision)[0]\n\n left_marking = [lateral_shift(w.transform, -w.lane_width * 0.5) for w in waypoints]\n right_marking = [lateral_shift(w.transform, w.lane_width * 0.5) for w in waypoints]\n\n polygon = left_marking + [x for x in reversed(right_marking)]\n polygon = [world_to_pixel(x) for x in polygon]\n\n if len(polygon) > 2:\n pygame.draw.polygon(map_surface, COLOR_WHITE, polygon, 10)\n pygame.draw.polygon(map_surface, COLOR_WHITE, polygon)\n\n if not waypoint.is_intersection:\n sample = waypoints[int(len(waypoints) / 2)]\n draw_lane_marking(\n lane_surface,\n [world_to_pixel(x) for x in left_marking],\n does_cross_solid_line(sample, -sample.lane_width * 1.1))\n draw_lane_marking(\n lane_surface,\n [world_to_pixel(x) for x in right_marking],\n does_cross_solid_line(sample, sample.lane_width * 1.1))\n \n # Dian: Do not draw them arrows\n # for n, wp in enumerate(waypoints):\n # if (n % 400) == 0:\n # draw_arrow(map_surface, wp.transform)\n \n actors = carla_world.get_actors()\n stops_transform = [actor.get_transform() for actor in actors if 'stop' in actor.type_id]\n font_size = world_to_pixel_width(1) \n font = pygame.font.SysFont('Arial', font_size, True)\n font_surface = font.render(\"STOP\", False, COLOR_ALUMINIUM_2)\n font_surface = pygame.transform.scale(font_surface, (font_surface.get_width(),font_surface.get_height() * 2))\n \n # Dian: do not draw stop sign\n \n # for stop in stops_transform:\n # draw_stop(map_surface,font_surface, stop)\n\n\n def world_to_pixel(self, location, offset=(0, 0)):\n x = self.scale * self._pixels_per_meter * (location.x - self._world_offset[0])\n y = self.scale * self._pixels_per_meter * (location.y - self._world_offset[1])\n return [int(x - offset[0]), int(y - offset[1])]\n\n def world_to_pixel_width(self, width):\n return int(self.scale * self._pixels_per_meter * width)\n\n def scale_map(self, scale):\n if scale != self.scale:\n self.scale = scale\n width = int(self.big_map_surface.get_width() * self.scale)\n self.surface = pygame.transform.smoothscale(self.big_map_surface, (width, width))\n\n\nclass ModuleWorld(object):\n \"\"\"\n There are 3 sets of surfaces:\n\n x_surface, hero_x_surface, and window_surface.\n\n x_surface's size covers the entire carla town map. It is constructed by getting\n all possible spaced-out waypoints and finding the difference between the max and\n the min. Its coordinate system is in the town coord sys.\n\n hero_x_surface is of size 1.5 * bev map size. It is centered closer to (but not exactly\n at) to the center of the resulting bev. Its origin has been shifted but the orientation\n still in town coord sys. Its larger size is required so that no info is lost when the\n rotation is performed, which makes the car location roughly at the bottom of the bev.\n\n window_surface is the actual bev, and its size is the actual bev size.\n\n Logic for rendering:\n\n First all actors are rendered on x_surface in city coord. Then a region close to the\n egovehicle is clipped and rendered onto hero_x_surface. Hero_x_surface is then rotated,\n and it just so happen the math checks out and the desired origin is right at the middle\n center of the image. The excess margins are trimmed to create the window_surface.\n\n Carla coordinate sys is forward is x, horizontal (not sure right or left) is y, height is z. In BEV,\n x is the height of the img, y is the width.\n \"\"\"\n\n def __init__(self, name, client, world, town_map, hero_actor):\n\n self.name = name\n self.server_fps = 0.0\n self.simulation_time = 0\n\n self.server_clock = pygame.time.Clock()\n\n # World data\n self.client = client\n self.world = world\n self.town_map = town_map\n self.actors_with_transforms = []\n # Store necessary modules\n self.module_hud = None\n self.module_input = None\n\n self.surface_size = [0, 0]\n self.prev_scaled_size = 0\n self.scaled_size = 0\n # Hero actor\n self.hero_actor = hero_actor\n self.hero_transform = hero_actor.get_transform()\n\n self.scale_offset = [0, 0]\n\n self.vehicle_id_surface = None\n self.result_surface = None\n\n self.traffic_light_surfaces = TrafficLightSurfaces()\n self.affected_traffic_light = None\n \n # Map info\n self.map_image = None\n self.border_round_surface = None\n self.original_surface_size = None\n # self.actors_surface = None\n \n self.self_surface: pygame.Surface = None\n self.vehicle_surface: pygame.Surface = None\n self.walker_surface: pygame.Surface = None\n \n self.hero_map_surface: pygame.Surface = None\n self.hero_lane_surface: pygame.Surface = None\n self.hero_self_surface: pygame.Surface = None\n self.hero_vehicle_surface: pygame.Surface = None\n self.hero_walker_surface: pygame.Surface = None\n self.hero_traffic_light_surface: pygame.Surface = None\n\n self.window_map_surface: pygame.Surface = None\n self.window_lane_surface: pygame.Surface = None\n self.window_self_surface: pygame.Surface = None\n self.window_vehicle_surface: pygame.Surface = None\n self.window_walker_surface: pygame.Surface = None\n self.window_traffic_light_surface: pygame.Surface = None\n\n self.hero_map_image = None\n self.hero_lane_image = None\n self.hero_self_image = None\n self.hero_vehicle_image = None\n self.hero_walker_image = None\n self.hero_traffic_image = None\n\n def get_rendered_surfaces(self):\n return (\n self.hero_map_image,\n self.hero_lane_image,\n # self.hero_self_image,\n self.hero_vehicle_image,\n self.hero_walker_image,\n self.hero_traffic_image,\n )\n\n def get_hero_measurements(self):\n \"\"\"\n Retrieve various stats about the egovehicle in the town coord sys.\n Returns:\n position: xyz in meter\n orientation: xy (not sure if normalized)\n veolcity: xyz velocity\n acceleration: xyz acceleration\n \"\"\"\n pos = self.hero_actor.get_location()\n ori = self.hero_actor.get_transform().get_forward_vector()\n vel = self.hero_actor.get_velocity()\n acc = self.hero_actor.get_acceleration()\n\n return {\n 'position': np.float32([pos.x, pos.y, pos.z]),\n 'orientation': np.float32([ori.x, ori.y]),\n 'velocity': np.float32([vel.x, vel.y, vel.z]),\n 'acceleration': np.float32([acc.x, acc.y, acc.z])\n }\n\n def start(self):\n \"\"\"\n Create the 3 sets of surfaces, and other miscellious surfaces.\n Returns:\n\n \"\"\"\n # Create Surfaces\n self.map_image = MapImage(self.world, self.town_map, PIXELS_PER_METER)\n\n # Store necessary modules\n self.module_hud = module_manager.get_module(MODULE_HUD)\n self.module_input = module_manager.get_module(MODULE_INPUT)\n \n self.window_width, self.window_height = self.module_hud.dim\n\n self.original_surface_size = min(self.module_hud.dim[0], self.module_hud.dim[1])\n self.surface_size = self.map_image.big_map_surface.get_width()\n\n self.scaled_size = int(self.surface_size)\n self.prev_scaled_size = int(self.surface_size)\n\n # Render Actors\n # self.actors_surface = pygame.Surface((self.map_image.map_surface.get_width(), self.map_image.map_surface.get_height()))\n # self.actors_surface.set_colorkey(COLOR_BLACK)\n self.vehicle_surface = pygame.Surface((self.map_image.map_surface.get_width(), self.map_image.map_surface.get_height()))\n self.vehicle_surface.set_colorkey(COLOR_BLACK)\n self.self_surface = pygame.Surface((self.map_image.map_surface.get_width(), self.map_image.map_surface.get_height()))\n self.self_surface.set_colorkey(COLOR_BLACK)\n self.walker_surface = pygame.Surface((self.map_image.map_surface.get_width(), self.map_image.map_surface.get_height()))\n self.walker_surface.set_colorkey(COLOR_BLACK)\n self.traffic_light_surface = pygame.Surface((self.map_image.map_surface.get_width(), self.map_image.map_surface.get_height()))\n self.traffic_light_surface.set_colorkey(COLOR_BLACK)\n\n self.vehicle_id_surface = pygame.Surface((self.surface_size, self.surface_size)).convert()\n self.vehicle_id_surface.set_colorkey(COLOR_BLACK)\n\n self.border_round_surface = pygame.Surface(self.module_hud.dim, pygame.SRCALPHA).convert()\n self.border_round_surface.set_colorkey(COLOR_WHITE)\n self.border_round_surface.fill(COLOR_BLACK)\n\n center_offset = (int(self.module_hud.dim[0] / 2), int(self.module_hud.dim[1] / 2))\n pygame.draw.circle(self.border_round_surface, COLOR_ALUMINIUM_1, center_offset, int(self.module_hud.dim[1] / 2))\n pygame.draw.circle(self.border_round_surface, COLOR_WHITE, center_offset, int((self.module_hud.dim[1] - 8) / 2))\n\n scaled_original_size = self.original_surface_size * 1.5\n # self.hero_surface = pygame.Surface((scaled_original_size, scaled_original_size)).convert()\n\n self.hero_map_surface = pygame.Surface((scaled_original_size, scaled_original_size)).convert()\n self.hero_lane_surface = pygame.Surface((scaled_original_size, scaled_original_size)).convert()\n self.hero_self_surface = pygame.Surface((scaled_original_size, scaled_original_size)).convert()\n self.hero_vehicle_surface = pygame.Surface((scaled_original_size, scaled_original_size)).convert()\n self.hero_walker_surface = pygame.Surface((scaled_original_size, scaled_original_size)).convert()\n self.hero_traffic_light_surface = pygame.Surface((scaled_original_size, scaled_original_size)).convert()\n \n self.window_map_surface = pygame.Surface((self.window_width, self.window_height)).convert()\n self.window_lane_surface = pygame.Surface((self.window_width, self.window_height)).convert()\n self.window_self_surface = pygame.Surface((self.window_width, self.window_height)).convert()\n self.window_vehicle_surface = pygame.Surface((self.window_width, self.window_height)).convert()\n self.window_walker_surface = pygame.Surface((self.window_width, self.window_height)).convert()\n self.window_traffic_light_surface = pygame.Surface((self.window_width, self.window_height)).convert()\n \n self.result_surface = pygame.Surface((self.surface_size, self.surface_size)).convert()\n self.result_surface.set_colorkey(COLOR_BLACK)\n\n # Start hero mode by default\n # self.select_hero_actor()\n # self.hero_actor.set_autopilot(False)\n self.module_input.wheel_offset = HERO_DEFAULT_SCALE\n self.module_input.control = carla.VehicleControl()\n\n weak_self = weakref.ref(self)\n # self.world.on_tick(lambda timestamp: ModuleWorld.on_world_tick(weak_self, timestamp))\n\n def tick(self, clock):\n actors = self.world.get_actors()\n self.actors_with_transforms = [(actor, actor.get_transform()) for actor in actors]\n if self.hero_actor is not None:\n self.hero_transform = self.hero_actor.get_transform()\n self.update_hud_info(clock)\n\n def update_hud_info(self, clock):\n \"\"\"\n Updates the Heads Up Display(HUD) text that shows the current status of the simulator.\n Args:\n clock ():\n\n Returns:\n\n \"\"\"\n hero_mode_text = []\n if self.hero_actor is not None:\n hero_speed = self.hero_actor.get_velocity()\n hero_speed_text = 3.6 * math.sqrt(hero_speed.x ** 2 + hero_speed.y ** 2 + hero_speed.z ** 2)\n \n affected_traffic_light_text = 'None'\n if self.affected_traffic_light is not None:\n state = self.affected_traffic_light.state\n if state == carla.libcarla.TrafficLightState.Green:\n affected_traffic_light_text = 'GREEN'\n elif state == carla.libcarla.TrafficLightState.Yellow:\n affected_traffic_light_text = 'YELLOW'\n else:\n affected_traffic_light_text = 'RED'\n\n affected_speed_limit_text = self.hero_actor.get_speed_limit()\n\n hero_mode_text = [\n 'Hero Mode: ON',\n 'Hero ID: %7d' % self.hero_actor.id,\n 'Hero Vehicle: %14s' % get_actor_display_name(self.hero_actor, truncate=14),\n 'Hero Speed: %3d km/h' % hero_speed_text,\n 'Hero Affected by:',\n ' Traffic Light: %12s' % affected_traffic_light_text,\n ' Speed Limit: %3d km/h' % affected_speed_limit_text\n ]\n else:\n hero_mode_text = ['Hero Mode: OFF']\n\n self.server_fps = self.server_clock.get_fps()\n self.server_fps = 'inf' if self.server_fps == float('inf') else round(self.server_fps)\n module_info_text = [\n 'Server: % 16s FPS' % self.server_fps,\n 'Client: % 16s FPS' % round(clock.get_fps()),\n 'Simulation Time: % 12s' % datetime.timedelta(seconds=int(self.simulation_time)),\n 'Map Name: %10s' % self.town_map.name,\n ]\n\n module_info_text = module_info_text\n module_hud = module_manager.get_module(MODULE_HUD)\n module_hud.add_info(self.name, module_info_text)\n module_hud.add_info('HERO', hero_mode_text)\n\n @staticmethod\n def on_world_tick(weak_self, timestamp):\n # print (timestamp)\n self = weak_self()\n if not self:\n return\n\n self.server_clock.tick()\n self.server_fps = self.server_clock.get_fps()\n self.simulation_time = timestamp.elapsed_seconds\n\n def _split_actors(self):\n \"\"\"\n Obtain a list of actors, including vehicles, traffic lights, speed limits, and pedestrians.\n Splits them into their own categories and return those lists individually. Additionally,\n add some near vehicles' stats into the heads up display.\n Returns:\n\n \"\"\"\n vehicles = []\n traffic_lights = []\n speed_limits = []\n walkers = []\n\n for actor_with_transform in self.actors_with_transforms:\n actor = actor_with_transform[0]\n if 'vehicle' in actor.type_id:\n vehicles.append(actor_with_transform)\n elif 'traffic_light' in actor.type_id:\n traffic_lights.append(actor_with_transform)\n elif 'speed_limit' in actor.type_id:\n speed_limits.append(actor_with_transform)\n elif 'walker' in actor.type_id:\n walkers.append(actor_with_transform)\n\n info_text = []\n if self.hero_actor is not None and len(vehicles) > 1:\n location = self.hero_transform.location\n vehicle_list = [x[0] for x in vehicles if x[0].id != self.hero_actor.id]\n\n def distance(v): return location.distance(v.get_location())\n for n, vehicle in enumerate(sorted(vehicle_list, key=distance)):\n if n > 15:\n break\n vehicle_type = get_actor_display_name(vehicle, truncate=22)\n info_text.append('% 5d %s' % (vehicle.id, vehicle_type))\n module_manager.get_module(MODULE_HUD).add_info(\n 'NEARBY VEHICLES',\n info_text)\n\n return (vehicles, traffic_lights, speed_limits, walkers)\n\n def get_bounding_box(self, actor):\n \"\"\"\n Get the bounding box of an actor. Todo: figure out why the last transform is required.\n Args:\n actor ():\n\n Returns:\n\n \"\"\"\n bb = actor.trigger_volume.extent\n corners = [carla.Location(x=-bb.x, y=-bb.y),\n carla.Location(x=bb.x, y=-bb.y),\n carla.Location(x=bb.x, y=bb.y),\n carla.Location(x=-bb.x, y=bb.y),\n carla.Location(x=-bb.x, y=-bb.y)]\n corners = [x + actor.trigger_volume.location for x in corners]\n t = actor.get_transform()\n t.transform(corners)\n return corners\n\n def _render_traffic_lights(self, surface, list_tl, world_to_pixel, world_to_pixel_width, from_snapshot=False):\n \"\"\"\n For every traffic light, draw onto |surface| the corresponding color of red, yellow, and green. The\n radius of the traffic lights are todo.\n Args:\n surface ():\n list_tl ():\n world_to_pixel ():\n world_to_pixel_width ():\n from_snapshot ():\n\n Returns:\n\n \"\"\"\n self.affected_traffic_light = None\n\n for tl in list_tl:\n if from_snapshot:\n world_pos = carla.Location(\n x=tl[\"location\"][\"x\"],\n y=tl[\"location\"][\"y\"],\n )\n else:\n world_pos = tl.get_location()\n pos = world_to_pixel(world_pos)\n # if self.hero_actor is not None and hasattr(tl, 'trigger_volume'):\n # corners = self.get_bounding_box(tl)\n # corners = [world_to_pixel(p) for p in corners]\n # tl_t = tl.get_transform()\n\n # transformed_tv = tl_t.transform(tl.trigger_volume.location)\n # hero_location = self.hero_actor.get_location()\n # d = hero_location.distance(transformed_tv)\n # s = Util.length(tl.trigger_volume.extent) + Util.length(self.hero_actor.bounding_box.extent)\n # if ( d <= s ):\n # Highlight traffic light\n # print (tl.state)\n # self.affected_traffic_light = tl\n # srf = self.traffic_light_surfaces.surfaces['h']\n # surface.blit(srf, srf.get_rect(center=pos))\n \n if from_snapshot:\n if tl[\"state\"] == int(tls.Red):\n # color = COLOR_SCARLET_RED_0\n color = COLOR_TRAFFIC_RED\n elif tl[\"state\"] == int(tls.Yellow):\n color = COLOR_TRAFFIC_YELLOW\n # color = COLOR_BUTTER_0\n elif tl[\"state\"] == int(tls.Green):\n color = COLOR_TRAFFIC_GREEN\n # color = COLOR_CHAMELEON_0\n else:\n continue # Unknown or off traffic light\n else:\n if tl.state == tls.Red:\n # color = COLOR_SCARLET_RED_0\n color = COLOR_TRAFFIC_RED\n elif tl.state == tls.Yellow:\n color = COLOR_TRAFFIC_YELLOW\n # color = COLOR_BUTTER_0\n elif tl.state == tls.Green:\n color = COLOR_TRAFFIC_GREEN\n # color = COLOR_CHAMELEON_0\n else:\n continue # Unknown or off traffic light\n \n # Draw circle instead of rectangle\n # bb = tl.bounding_box.extent\n radius = world_to_pixel_width(1.5)\n pygame.draw.circle(surface, color, pos, radius)\n \n # corners = [\n # (pos[0]-radius, pos[1]-radius),\n # (pos[0]+radius, pos[1]-radius),\n # (pos[0]+radius, pos[1]+radius),\n # (pos[0]-radius, pos[1]+radius)\n # ]\n # # corners = [world_to_pixel(p) for p in corners]\n # pygame.draw.polygon(surface, color, corners)\n \n # srf = self.traffic_light_surfaces.surfaces[tl.state]\n # surface.blit(srf, srf.get_rect(center=pos))\n\n def _render_speed_limits(self, surface, list_sl, world_to_pixel, world_to_pixel_width):\n\n font_size = world_to_pixel_width(2)\n radius = world_to_pixel_width(2)\n font = pygame.font.SysFont('Arial', font_size)\n\n for sl in list_sl:\n\n x, y = world_to_pixel(sl.get_location())\n\n # Render speed limit\n white_circle_radius = int(radius * 0.75)\n\n pygame.draw.circle(surface, COLOR_SCARLET_RED_1, (x, y), radius)\n pygame.draw.circle(surface, COLOR_ALUMINIUM_0, (x, y), white_circle_radius)\n\n limit = sl.type_id.split('.')[2]\n font_surface = font.render(limit, True, COLOR_ALUMINIUM_5)\n\n # Blit\n if self.hero_actor is not None:\n # Rotate font surface with respect to hero vehicle front\n angle = -self.hero_transform.rotation.yaw - 90.0\n font_surface = pygame.transform.rotate(font_surface, angle)\n offset = font_surface.get_rect(center=(x, y))\n surface.blit(font_surface, offset)\n\n else:\n surface.blit(font_surface, (x - radius / 2, y - radius / 2))\n\n def _render_walkers(self, surface, list_w, world_to_pixel, from_snapshot=False):\n \"\"\"\n Map each walker to their corners in world coord. Then map the coords to pixels, and finally draw them onto\n the Surfaces.\n Args:\n surface ():\n list_w ():\n world_to_pixel ():\n from_snapshot ():\n\n Returns:\n\n \"\"\"\n # print (\"Walkers\")\n\n for w in list_w:\n # color = COLOR_PLUM_0\n color = COLOR_WHITE\n # Compute bounding box points\n if from_snapshot:\n bb = w[\"bbox\"]\n corners = [\n carla.Location(x=-bb[\"x\"], y=-bb[\"y\"]),\n carla.Location(x=bb[\"x\"], y=-bb[\"y\"]),\n carla.Location(x=bb[\"x\"], y=bb[\"y\"]),\n carla.Location(x=-bb[\"x\"], y=bb[\"y\"])\n ]\n w_location = carla.Location(x=w[\"location\"][\"x\"], y=w[\"location\"][\"y\"])\n corners = [corner + w_location for corner in corners]\n else:\n if not hasattr(w[0], 'bounding_box'):\n continue\n\n bb = w[0].bounding_box.extent\n corners = [\n carla.Location(x=-bb.x, y=-bb.y),\n carla.Location(x=bb.x, y=-bb.y),\n carla.Location(x=bb.x, y=bb.y),\n carla.Location(x=-bb.x, y=bb.y)\n ]\n w[1].transform(corners)\n \n corners = [world_to_pixel(p) for p in corners]\n # print (corners)\n pygame.draw.polygon(surface, color, corners)\n\n def _render_vehicles(self, vehicle_surface, self_surface, list_v, world_to_pixel, from_snapshot=False):\n # print (\"rendered a car?!\")\n for v in list_v:\n # color = COLOR_SKY_BLUE_0\n color = COLOR_WHITE\n\n if not from_snapshot and v[0].attributes['role_name'] == 'hero':\n # Do not render othre vehicles\n # print (v[1])\n surface = self_surface\n else:\n surface = vehicle_surface\n \n # continue # Do not render itself\n # Compute bounding box points\n if from_snapshot:\n bb = v[\"bbox\"]\n corners = [\n carla.Location(x=-bb[\"x\"], y=-bb[\"y\"]),\n carla.Location(x=bb[\"x\"], y=-bb[\"y\"]),\n carla.Location(x=bb[\"x\"], y=bb[\"y\"]),\n carla.Location(x=-bb[\"x\"], y=bb[\"y\"])\n ]\n v_location = carla.Location(x=v[\"location\"][\"x\"], y=v[\"location\"][\"y\"])\n corners = [corner + v_location for corner in corners]\n else:\n bb = v[0].bounding_box.extent\n corners = [carla.Location(x=-bb.x, y=-bb.y),\n carla.Location(x=-bb.x, y=bb.y),\n carla.Location(x=bb.x, y=bb.y),\n carla.Location(x=bb.x, y=-bb.y)\n ]\n v[1].transform(corners)\n # print (\"Vehicle\")\n corners = [world_to_pixel(p) for p in corners]\n pygame.draw.polygon(surface, color, corners)\n # pygame.draw.lines(surface, color, False, corners, int(math.ceil(4.0 * self.map_image.scale)))\n\n def render_actors(\n self, vehicle_surface, self_surface, walker_surface,\n traffic_light_surface, vehicles, traffic_lights,\n speed_limits, walkers, from_snapshot=False):\n # Static actors\n \n # TODO: render traffic lights and speed limits on respective channels\n if from_snapshot:\n self._render_traffic_lights(\n traffic_light_surface, traffic_lights,\n self.map_image.world_to_pixel,\n self.map_image.world_to_pixel_width, from_snapshot=True)\n else:\n self._render_traffic_lights(\n traffic_light_surface,\n [tl[0] for tl in traffic_lights],\n self.map_image.world_to_pixel,\n self.map_image.world_to_pixel_width, from_snapshot=False)\n # self._render_speed_limits(\n # surface, [sl[0] for sl in speed_limits],\n # self.map_image.world_to_pixel,\n # self.map_image.world_to_pixel_width)\n\n # Dynamic actors\n self._render_vehicles(\n vehicle_surface, self_surface, vehicles,\n self.map_image.world_to_pixel, from_snapshot=from_snapshot)\n self._render_walkers(\n walker_surface, walkers,\n self.map_image.world_to_pixel, from_snapshot=from_snapshot)\n\n def clip_surfaces(self, clipping_rect):\n # self.actors_surface.set_clip(clipping_rect)\n self.vehicle_surface.set_clip(clipping_rect)\n self.walker_surface.set_clip(clipping_rect)\n self.traffic_light_surface.set_clip(clipping_rect)\n self.vehicle_id_surface.set_clip(clipping_rect)\n self.result_surface.set_clip(clipping_rect)\n\n def _compute_scale(self, scale_factor):\n m = self.module_input.mouse_pos\n\n # Percentage of surface where mouse position is actually\n px = (m[0] - self.scale_offset[0]) / float(self.prev_scaled_size)\n py = (m[1] - self.scale_offset[1]) / float(self.prev_scaled_size)\n\n # Offset will be the previously accumulated offset added with the\n # difference of mouse positions in the old and new scales\n diff_between_scales = ((float(self.prev_scaled_size) * px) - (float(self.scaled_size) * px),\n (float(self.prev_scaled_size) * py) - (float(self.scaled_size) * py))\n\n self.scale_offset = (self.scale_offset[0] + diff_between_scales[0],\n self.scale_offset[1] + diff_between_scales[1])\n\n # Update previous scale\n self.prev_scaled_size = self.scaled_size\n\n # Scale performed\n self.map_image.scale_map(scale_factor)\n\n def render(self, display, snapshot=None):\n \"\"\"\n Does the heavylifting of rendering the objects in the road scene onto the BEV occupany maps.\n \"\"\"\n if snapshot is None and self.actors_with_transforms is None:\n return\n\n self.result_surface.fill(COLOR_BLACK)\n \n if snapshot is None:\n vehicles, traffic_lights, speed_limits, walkers = self._split_actors()\n else:\n vehicles = snapshot[\"vehicles\"]\n traffic_lights = snapshot[\"traffic_lights\"]\n speed_limits = []\n walkers = snapshot[\"walkers\"]\n \n scale_factor = self.module_input.wheel_offset\n self.scaled_size = int(self.map_image.width * scale_factor)\n\n if self.scaled_size != self.prev_scaled_size:\n self._compute_scale(scale_factor)\n\n ############################## Render all actors in city coord on the x_surface\n self.vehicle_surface.fill(COLOR_BLACK)\n self.walker_surface.fill(COLOR_BLACK)\n self.traffic_light_surface.fill(COLOR_BLACK)\n\n self.render_actors(\n # self.actors_surface,\n self.vehicle_surface, self.self_surface, self.walker_surface,\n self.traffic_light_surface, vehicles, traffic_lights,\n speed_limits, walkers, from_snapshot=snapshot is not None)\n\n # Render Ids\n self.module_hud.render_vehicles_ids(\n self.vehicle_id_surface, vehicles,\n self.map_image.world_to_pixel, self.hero_actor, self.hero_transform)\n\n # Blit surfaces\n surfaces = [(self.map_image.map_surface, (0, 0))]\n # surfaces = ((self.map_image.map_surface, (0, 0)),\n # # (self.actors_surface, (0, 0)),\n # # (self.vehicle_id_surface, (0, 0)),\n # )\n\n ############################## Clip a region from x_surface onto hero_x_surface. Then rotate\n\n # compute the angle the vehicle is facing. Yaw is parallel to the ground.\n center_offset = (0, 0)\n angle = 0.0 if self.hero_actor is None else self.hero_transform.rotation.yaw + 90\n self.traffic_light_surfaces.rotozoom(-angle, self.map_image.scale)\n\n # hero_front is a normalized vector of the egovehicle's orientation\n if self.hero_actor is not None:\n if snapshot is None:\n hero_front = self.hero_transform.get_forward_vector()\n hero_location_screen = self.map_image.world_to_pixel(\n self.hero_transform.location)\n else:\n hero_location = snapshot[\"player\"][\"transform\"][\"location\"]\n hero_location = carla.Location(\n x=hero_location[\"x\"],\n y=hero_location[\"y\"],\n z=hero_location[\"z\"],\n )\n hero_location_screen = self.map_image.world_to_pixel(hero_location)\n\n hero_orientation = snapshot[\"player\"][\"transform\"][\"orientation\"]\n hero_front = carla.Location(x=hero_orientation[\"x\"], y=hero_orientation[\"y\"])\n\n # The offset is computed to reflect which region on the city coord from x_surface we want.\n # It is the upper left hand corner of the resulting hero_x_surface.\n # We starts at [0, 0], meaning we start with the upper left corner of the city coord. Then\n # we move to the egovehicle's loc. We then move a little to the left and up, so that the\n # center of hero_x_surface aligns with the egovehicle's loc. This is still not enough,\n # as we actual want the region at in front of the egovehicle, but not including the egovehicle.\n # PIXELS_AHEAD_VEHICLE represents that desire distance. Right now, it is set to\n # self.hero_map_surface.get_width() / 2 + (2_meters_in_front_where_the_camera_is).\n # The egovehicle could be facing at an agle, thus we use hero_front to determine the amount\n # of the pixel ahead to each axis.\n #\n # Note that after rotation, the math checks out, and hero_x_surface's center is exactly the\n # center we want for the bev.\n offset = [0, 0]\n offset[0] += hero_location_screen[0] - self.hero_map_surface.get_width() / 2\n offset[0] += hero_front.x * PIXELS_AHEAD_VEHICLE\n offset[1] += hero_location_screen[1] - self.hero_map_surface.get_height() / 2\n offset[1] += hero_front.y * PIXELS_AHEAD_VEHICLE\n\n # Apply clipping rect\n clipping_rect = pygame.Rect(\n offset[0], offset[1],\n self.hero_map_surface.get_width(),\n self.hero_map_surface.get_height())\n\n self.clip_surfaces(clipping_rect)\n self.border_round_surface.set_clip(clipping_rect)\n\n # self.hero_surface.fill(COLOR_ALUMINIUM_4)\n # self.hero_surface.blit(self.result_surface, (-translation_offset[0],\n # -translation_offset[1]))\n\n # self.hero_map_surface.blit\n\n # self.hero_self_surface.fill(COLOR_BLACK)\n self.hero_map_surface.fill(COLOR_BLACK)\n self.hero_vehicle_surface.fill(COLOR_BLACK)\n self.hero_walker_surface.fill(COLOR_BLACK)\n self.hero_traffic_light_surface.fill(COLOR_BLACK)\n\n # self.hero_self_surface.blit(self.self_surface, (-offset[0], -offset[1]))\n self.hero_map_surface.blit(self.map_image.map_surface, (-offset[0], -offset[1]))\n self.hero_lane_surface.blit(self.map_image.lane_surface, (-offset[0], -offset[1]))\n self.hero_vehicle_surface.blit(self.vehicle_surface, (-offset[0], -offset[1]))\n self.hero_walker_surface.blit(self.walker_surface, (-offset[0], -offset[1]))\n self.hero_traffic_light_surface.blit(\n self.traffic_light_surface, (-offset[0], -offset[1]))\n\n\n # rotated_result_surface = pygame.transform.rotozoom(\n # self.hero_surface, angle, 0.9).convert()\n\n # Rotate: map/vehicle/walker surface\n # TODO: traffic lights and speed limits surface\n rz = pygame.transform.rotozoom\n\n rotated_map_surface = rz(self.hero_map_surface, angle, 1.0).convert()\n rotated_lane_surface = rz(self.hero_lane_surface, angle, 1.0).convert()\n rotated_vehicle_surface = rz(self.hero_vehicle_surface, angle, 1.0).convert()\n rotated_walker_surface = rz(self.hero_walker_surface, angle, 1.0).convert()\n rotated_traffic_surface = rz(self.hero_traffic_light_surface, angle, 1.0).convert()\n # rotated_self_surface = rz(self.hero_self_surface, angle, 0.9).convert()\n\n # This is a neat way to copy the correct region from hero_x_surface onto x_surface.\n # A precondition here is that the center of hero_x_surface is exactly the center\n # for the x_surface. .get_rect(center=center) will obtain a rectangle the same\n # dim as rotated_x_surface, but the center is now in the window_x_surface's coord\n # sys. This way, when rotated_x_surface is rendered onto window_x_surface, the unwanted\n # margins are outside the blit area.\n center = (display.get_width() / 2, display.get_height() / 2)\n rotation_map_pivot = rotated_map_surface.get_rect(center=center)\n rotation_lane_pivot = rotated_lane_surface.get_rect(center=center)\n rotation_vehicle_pivot = rotated_vehicle_surface.get_rect(center=center)\n rotation_walker_pivot = rotated_walker_surface.get_rect(center=center)\n rotation_traffic_pivot = rotated_traffic_surface.get_rect(center=center)\n # rotation_self_pivot = rotated_self_surface.get_rect(center=center)\n\n self.window_map_surface.blit(rotated_map_surface, rotation_map_pivot)\n self.window_lane_surface.blit(rotated_lane_surface, rotation_lane_pivot)\n self.window_vehicle_surface.blit(rotated_vehicle_surface, rotation_vehicle_pivot)\n self.window_walker_surface.blit(rotated_walker_surface, rotation_walker_pivot)\n self.window_traffic_light_surface.blit(\n rotated_traffic_surface, rotation_traffic_pivot)\n # self.window_self_surface.blit(rotated_self_surface, rotation_self_pivot)\n\n make_image = lambda x: np.swapaxes(pygame.surfarray.array3d(x), 0, 1).mean(axis=-1)\n\n # Save surface as rgb array\n self.hero_map_image = make_image(self.window_map_surface)\n self.hero_lane_image = make_image(self.window_lane_surface)\n self.hero_vehicle_image = make_image(self.window_vehicle_surface)\n self.hero_walker_image = make_image(self.window_walker_surface)\n self.hero_traffic_image = np.swapaxes(\n pygame.surfarray.array3d(self.window_traffic_light_surface),\n 0, 1)\n # self.hero_self_image = np.swapaxes(\n # pygame.surfarray.array3d(self.window_self_surface),0,1).mean(axis=-1)\n else:\n # Translation offset\n translation_offset = (\n self.module_input.mouse_offset[0] * scale_factor + self.scale_offset[0],\n self.module_input.mouse_offset[1] * scale_factor + self.scale_offset[1])\n center_offset = (abs(display.get_width() - self.surface_size) / 2 * scale_factor, 0)\n\n # Apply clipping rect\n clipping_rect = pygame.Rect(\n -translation_offset[0] - center_offset[0], -translation_offset[1],\n self.module_hud.dim[0], self.module_hud.dim[1])\n self.clip_surfaces(clipping_rect)\n Util.blits(self.result_surface, surfaces)\n\n display.blit(\n self.result_surface,\n (translation_offset[0] + center_offset[0], translation_offset[1]))\n\n\n# ==============================================================================\n# -- Input -----------------------------------------------------------\n# ==============================================================================\n\n\nclass ModuleInput(object):\n def __init__(self, name):\n self.name = name\n self.mouse_pos = (0, 0)\n self.mouse_offset = [0.0, 0.0]\n self.wheel_offset = 0.1\n self.wheel_amount = 0.025\n self._steer_cache = 0.0\n self.control = None\n self._autopilot_enabled = False\n\n def start(self):\n hud = module_manager.get_module(MODULE_HUD)\n # hud.notification(\"Press 'H' or '?' for help.\", seconds=4.0)\n\n def render(self, display, snapshot=None):\n pass\n\n def tick(self, clock):\n self.parse_input(clock)\n\n def _parse_events(self):\n self.mouse_pos = pygame.mouse.get_pos()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit_game()\n elif event.type == pygame.KEYUP:\n if self._is_quit_shortcut(event.key):\n exit_game()\n elif event.key == K_h or (event.key == K_SLASH and pygame.key.get_mods() & KMOD_SHIFT):\n module_hud = module_manager.get_module(MODULE_HUD)\n module_hud.help.toggle()\n elif event.key == K_TAB:\n module_world = module_manager.get_module(MODULE_WORLD)\n module_hud = module_manager.get_module(MODULE_HUD)\n if module_world.hero_actor is None:\n module_world.select_hero_actor()\n self.wheel_offset = HERO_DEFAULT_SCALE\n self.control = carla.VehicleControl()\n module_hud.notification('Hero Mode')\n else:\n self.wheel_offset = MAP_DEFAULT_SCALE\n self.mouse_offset = [0, 0]\n self.mouse_pos = [0, 0]\n module_world.scale_offset = [0, 0]\n module_world.hero_actor = None\n module_hud.notification('Map Mode')\n elif event.key == K_F1:\n module_hud = module_manager.get_module(MODULE_HUD)\n module_hud.show_info = not module_hud.show_info\n elif event.key == K_i:\n module_hud = module_manager.get_module(MODULE_HUD)\n module_hud.show_actor_ids = not module_hud.show_actor_ids\n elif isinstance(self.control, carla.VehicleControl):\n if event.key == K_q:\n self.control.gear = 1 if self.control.reverse else -1\n elif event.key == K_m:\n self.control.manual_gear_shift = not self.control.manual_gear_shift\n world = module_manager.get_module(MODULE_WORLD)\n self.control.gear = world.hero_actor.get_control().gear\n module_hud = module_manager.get_module(MODULE_HUD)\n module_hud.notification('%s Transmission' % (\n 'Manual' if self.control.manual_gear_shift else 'Automatic'))\n elif self.control.manual_gear_shift and event.key == K_COMMA:\n self.control.gear = max(-1, self.control.gear - 1)\n elif self.control.manual_gear_shift and event.key == K_PERIOD:\n self.control.gear = self.control.gear + 1\n elif event.key == K_p:\n world = module_manager.get_module(MODULE_WORLD)\n if world.hero_actor is not None:\n self._autopilot_enabled = not self._autopilot_enabled\n world.hero_actor.set_autopilot(self._autopilot_enabled)\n module_hud = module_manager.get_module(MODULE_HUD)\n module_hud.notification('Autopilot %s' % ('On' if self._autopilot_enabled else 'Off'))\n elif event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 4:\n self.wheel_offset += self.wheel_amount\n if self.wheel_offset >= 1.0:\n self.wheel_offset = 1.0\n elif event.button == 5:\n self.wheel_offset -= self.wheel_amount\n if self.wheel_offset <= 0.1:\n self.wheel_offset = 0.1\n\n def _parse_keys(self, milliseconds):\n keys = pygame.key.get_pressed()\n self.control.throttle = 1.0 if keys[K_UP] or keys[K_w] else 0.0\n steer_increment = 5e-4 * milliseconds\n if keys[K_LEFT] or keys[K_a]:\n self._steer_cache -= steer_increment\n elif keys[K_RIGHT] or keys[K_d]:\n self._steer_cache += steer_increment\n else:\n self._steer_cache = 0.0\n self._steer_cache = min(0.7, max(-0.7, self._steer_cache))\n self.control.steer = round(self._steer_cache, 1)\n self.control.brake = 1.0 if keys[K_DOWN] or keys[K_s] else 0.0\n self.control.hand_brake = keys[K_SPACE]\n\n def _parse_mouse(self):\n if pygame.mouse.get_pressed()[0]:\n x, y = pygame.mouse.get_pos()\n self.mouse_offset[0] += (1.0 / self.wheel_offset) * (x - self.mouse_pos[0])\n self.mouse_offset[1] += (1.0 / self.wheel_offset) * (y - self.mouse_pos[1])\n self.mouse_pos = (x, y)\n\n def parse_input(self, clock):\n self._parse_events()\n self._parse_mouse()\n if not self._autopilot_enabled:\n if isinstance(self.control, carla.VehicleControl):\n self._parse_keys(clock.get_time())\n self.control.reverse = self.control.gear < 0\n world = module_manager.get_module(MODULE_WORLD)\n # if (world.hero_actor is not None):\n # world.hero_actor.apply_control(self.control)\n\n @staticmethod\n def _is_quit_shortcut(key):\n return (key == K_ESCAPE) or (key == K_q and pygame.key.get_mods() & KMOD_CTRL)\n\n\n# ==============================================================================\n# -- Global Objects ------------------------------------------------------------\n# ==============================================================================\nmodule_manager = ModuleManager()\n\n# ==============================================================================\n# bradyz: Wrap all this --------------------------------------------------------\n# ==============================================================================\nclass Wrapper(object):\n clock = None\n display = None\n world_module = None\n\n @classmethod\n def init(cls, client, world, carla_map, player):\n os.environ['SDL_VIDEODRIVER'] = 'dummy'\n\n module_manager.clear_modules()\n\n pygame.init()\n display = pygame.display.set_mode((200, 200), 0, 32)\n pygame.display.flip()\n\n # Set map drawer module\n input_module = ModuleInput(MODULE_INPUT)\n hud_module = ModuleHUD(MODULE_HUD, 200, 200)\n world_module = ModuleWorld(MODULE_WORLD, client, world, carla_map, player)\n\n # Register Modules\n module_manager.register_module(world_module)\n module_manager.register_module(hud_module)\n module_manager.register_module(input_module)\n module_manager.start_modules()\n\n cls.world_module = world_module\n cls.display = display\n cls.clock = pygame.time.Clock()\n\n @classmethod\n def tick(cls):\n module_manager.tick(cls.clock)\n module_manager.render(cls.display)\n\n @classmethod\n def get_observations(cls):\n road, lane, vehicle, pedestrian, traffic = cls.world_module.get_rendered_surfaces()\n\n result = cls.world_module.get_hero_measurements()\n result.update({\n 'road': np.uint8(road),\n 'lane': np.uint8(lane),\n 'vehicle': np.uint8(vehicle),\n 'pedestrian': np.uint8(pedestrian),\n 'traffic': np.uint8(traffic),\n })\n\n pygame.display.flip()\n\n return result\n\n @staticmethod\n def clear():\n module_manager.clear_modules()\n\n @classmethod\n def render_world(cls):\n map_surface = cls.world_module.map_image.big_map_surface\n map_image = np.swapaxes(pygame.surfarray.array3d(map_surface), 0, 1)\n\n return map_image\n\n @classmethod\n def world_to_pixel(cls, pos):\n return cls.world_module.map_image.world_to_pixel(pos)\n"
] | [
[
"numpy.float32",
"numpy.uint8"
]
] |
stjordanis/datar | [
"1218a549e2f0547c7b5a824ca6d9adf1bf96ba46"
] | [
"datar/base/trig_hb.py"
] | [
"\"\"\"Trigonometric and Hyperbolic Functions\"\"\"\n\nfrom typing import Callable\n\nimport numpy\nfrom pipda import register_func\n\nfrom ..core.contexts import Context\nfrom ..core.types import FloatOrIter\nfrom .constants import pi\n\n\ndef _register_trig_hb_func(name: str, np_name: str, doc: str) -> Callable:\n \"\"\"Register trigonometric and hyperbolic function\"\"\"\n np_fun = getattr(numpy, np_name)\n if name.endswith(\"pi\"):\n func = lambda x: np_fun(x * pi)\n else:\n # ufunc cannot set context\n func = lambda x: np_fun(x)\n\n func = register_func(None, context=Context.EVAL, func=func)\n func.__name__ = name\n func.__doc__ = doc\n return func\n\n\nsin = _register_trig_hb_func(\n \"sin\",\n \"sin\",\n doc=\"\"\"The sine function\n\nArgs:\n x: a numeric value or iterable\n\nReturns:\n The sine value of `x`\n\"\"\",\n)\n\ncos = _register_trig_hb_func(\n \"cos\",\n \"cos\",\n doc=\"\"\"The cosine function\n\nArgs:\n x: a numeric value or iterable\n\nReturns:\n The cosine value of `x`\n\"\"\",\n)\n\ntan = _register_trig_hb_func(\n \"tan\",\n \"tan\",\n doc=\"\"\"The tangent function\n\nArgs:\n x: a numeric value or iterable\n\nReturns:\n The tangent value of `x`\n\"\"\",\n)\n\nacos = _register_trig_hb_func(\n \"acos\",\n \"arccos\",\n doc=\"\"\"The arc-cosine function\n\nArgs:\n x: a numeric value or iterable\n\nReturns:\n The arc-cosine value of `x`\n\"\"\",\n)\n\nasin = _register_trig_hb_func(\n \"acos\",\n \"arcsin\",\n doc=\"\"\"The arc-sine function\n\nArgs:\n x: a numeric value or iterable\n\nReturns:\n The arc-sine value of `x`\n\"\"\",\n)\n\natan = _register_trig_hb_func(\n \"acos\",\n \"arctan\",\n doc=\"\"\"The arc-sine function\n\nArgs:\n x: a numeric value or iterable\n\nReturns:\n The arc-sine value of `x`\n\"\"\",\n)\n\nsinpi = _register_trig_hb_func(\n \"sinpi\",\n \"sin\",\n doc=\"\"\"The sine function\n\nArgs:\n x: a numeric value or iterable, which is the multiple of pi\n\nReturns:\n The sine value of `x`\n\"\"\",\n)\n\ncospi = _register_trig_hb_func(\n \"cospi\",\n \"cos\",\n doc=\"\"\"The cosine function\n\nArgs:\n x: a numeric value or iterable, which is the multiple of pi\n\nReturns:\n The cosine value of `x`\n\"\"\",\n)\n\ntanpi = _register_trig_hb_func(\n \"tanpi\",\n \"tan\",\n doc=\"\"\"The tangent function\n\nArgs:\n x: a numeric value or iterable, which is the multiple of pi\n\nReturns:\n The tangent value of `x`\n\"\"\",\n)\n\ncosh = _register_trig_hb_func(\n \"cosh\",\n \"cosh\",\n doc=\"\"\"Hyperbolic cosine\n\nArgs:\n x: a numeric value or iterable\n\nReturns:\n The hyperbolic cosine value of `x`\n\"\"\",\n)\n\nsinh = _register_trig_hb_func(\n \"sinh\",\n \"sinh\",\n doc=\"\"\"Hyperbolic sine\n\nArgs:\n x: a numeric value or iterable\n\nReturns:\n The hyperbolic sine value of `x`\n\"\"\",\n)\n\ntanh = _register_trig_hb_func(\n \"tanh\",\n \"tanh\",\n doc=\"\"\"Hyperbolic tangent\n\nArgs:\n x: a numeric value or iterable\n\nReturns:\n The hyperbolic tangent value of `x`\n\"\"\",\n)\n\nacosh = _register_trig_hb_func(\n \"acosh\",\n \"arccosh\",\n doc=\"\"\"Hyperbolic arc-cosine\n\nArgs:\n x: a numeric value or iterable\n\nReturns:\n The hyperbolic arc-cosine value of `x`\n\"\"\",\n)\n\nasinh = _register_trig_hb_func(\n \"asinh\",\n \"arcsinh\",\n doc=\"\"\"Hyperbolic arc-sine\n\nArgs:\n x: a numeric value or iterable\n\nReturns:\n The hyperbolic arc-sine value of `x`\n\"\"\",\n)\n\natanh = _register_trig_hb_func(\n \"atanh\",\n \"arctanh\",\n doc=\"\"\"Hyperbolic arc-tangent\n\nArgs:\n x: a numeric value or iterable\n\nReturns:\n The hyperbolic arc-tangent value of `x`\n\"\"\",\n)\n\n\n@register_func(None, context=Context.EVAL)\ndef atan2(y: FloatOrIter, x: FloatOrIter) -> FloatOrIter:\n \"\"\"Calculates the angle between the x-axis and the vector (0,0) -> (x,y)\n\n Args:\n y: and\n x: The end coordinates of the vector\n\n Returns:\n The angle between x-axis and vector (0,0) -> (x,y)\n \"\"\"\n return numpy.arctan2(y, x)\n"
] | [
[
"numpy.arctan2"
]
] |
Skywalker-official/Salary-vs-Experience-Prediction-SLR- | [
"e55167f29e91111f716bab2b6f7f23e6efb50827"
] | [
"simple_linear_regression_template.py"
] | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Dec 28 04:56:05 2018\n\n@author: skywalker\n\"\"\"\n\n# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing the dataset\ndataset = pd.read_csv('Salary_Data.csv')\nX = dataset.iloc[:, :-1].values\ny = dataset.iloc[:, 1].values\n\n# Splitting the dataset into the Training set and Test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)\n\n# Feature Scaling\n\"\"\"from sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train)\nX_test = sc_X.transform(X_test)\nsc_y = StandardScaler()\ny_train = sc_y.fit_transform(y_train)\"\"\"\n\n# fitting linear regression to the training set\nfrom sklearn.linear_model import LinearRegression\nregressor = LinearRegression()\nregressor.fit(X_train, y_train)\n\n# predicting the test set result\ny_pred = regressor.predict(X_test)\n\n# visualizing the training set result\nplt.scatter(X_train, y_train, color = 'red')\nplt.plot(X_train, regressor.predict(X_train), color = 'blue')\nplt.title('Salary vs Experiennce (Training set)')\nplt.xlabel('Years of Experience')\nplt.ylabel('Salary')\nplt.show()\n\n# visualizing the test set result\nplt.scatter(X_test, y_test, color = 'purple')\nplt.plot(X_train, regressor.predict(X_train), color = 'blue')\nplt.title('Salary vs Experiennce (Test set)')\nplt.xlabel('Years of Experience')\nplt.ylabel('Salary')\nplt.show()"
] | [
[
"pandas.read_csv",
"sklearn.linear_model.LinearRegression",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.scatter"
]
] |
maximecharpentierdata/link-prediction | [
"0c68ba7047b233c193541125711bdbf75b639907"
] | [
"src/metadata/features.py"
] | [
"from typing import List, Tuple\n\nimport networkx as nx\nimport numpy as np\nimport pandas as pd\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom tqdm import tqdm\n\n\n# Metadata based features\ndef metadata_features_extractor(\n graph: nx.Graph, samples: List[Tuple[str, str]], path: str\n) -> np.ndarray:\n \"\"\"Generates metadata based features\n\n Args:\n graph (nx.Graph): Graph\n samples (List[Tuple[str, str]]): Edge samples\n path (str): Path for node information\n\n Returns:\n np.ndarray: Features\n \"\"\"\n feature_vector = []\n df = pd.read_csv(path, header=None)\n df.columns = [\n \"id\",\n \"publication_year\",\n \"title\",\n \"authors\",\n \"journal_name\",\n \"abstract\",\n ]\n\n df = df.groupby(\"id\")\n\n for edge in tqdm(samples):\n source_node, target_node = edge[0], edge[1]\n source_row = df.get_group(int(source_node)).iloc[0]\n target_row = df.get_group(int(target_node)).iloc[0]\n\n # source_row = df[df[\"id\"] == int(source_node)].iloc[0]\n # target_row = df[df[\"id\"] == int(target_node)].iloc[0]\n\n if type(source_row[\"authors\"]) is not str:\n source_authors = []\n else:\n source_authors = source_row[\"authors\"].split(\", \")\n if type(target_row[\"authors\"]) is not str:\n target_authors = []\n else:\n target_authors = target_row[\"authors\"].split(\", \")\n\n number_of_common_authors = len(\n set(source_authors).intersection(set(target_authors))\n )\n\n source_year = int(source_row[\"publication_year\"])\n target_year = int(target_row[\"publication_year\"])\n\n year_difference = abs(source_year - target_year)\n\n source_title = source_row[\"title\"].split()\n target_title = target_row[\"title\"].split()\n\n title_difference = len(set(source_title).intersection(set(target_title)))\n\n feature_vector.append(\n np.array([number_of_common_authors, year_difference, title_difference])\n )\n return np.array(feature_vector)\n\n\n# Textual based features\ndef _compute_tfidf(\n graph: nx.Graph, samples: List[Tuple[str, str]], path: str, num_features: int = 2500\n):\n df = pd.read_csv(path, header=None)\n df.columns = [\n \"id\",\n \"publication_year\",\n \"title\",\n \"authors\",\n \"journal_name\",\n \"abstract\",\n ]\n\n df = df.groupby(\"id\")\n source_abstracts = []\n target_abstracts = []\n for edge in tqdm(samples):\n source_node, target_node = edge[0], edge[1]\n source_row = df.get_group(int(source_node)).iloc[0]\n target_row = df.get_group(int(target_node)).iloc[0]\n source_abstracts.append(source_row[\"abstract\"])\n target_abstracts.append(target_row[\"abstract\"])\n\n vectorizer = TfidfVectorizer(\n lowercase=True, stop_words=\"english\", max_features=num_features\n )\n all_abstracts = source_abstracts + target_abstracts\n all_features = vectorizer.fit_transform(all_abstracts)\n\n source_features = all_features[: len(source_abstracts), :].todense()\n target_features = all_features[len(source_abstracts) :, :].todense()\n\n multiplied = np.multiply(source_features, target_features)\n\n summed = np.sum(multiplied, axis=1)\n\n return source_features, target_features\n\n\ndef tfidf_abstract_extractor(\n graph: nx.Graph, samples: List[Tuple[str, str]], path: str\n) -> np.ndarray:\n \"\"\"Computes TFIDF based features\n\n Args:\n graph (nx.Graph): Graph\n samples (List[Tuple[str, str]]): Edge samples\n path (str): Path for node information\n\n Returns:\n np.ndarray: Features\n \"\"\"\n source_features, target_features = _compute_tfidf(graph, samples, path)\n multiplied = np.multiply(source_features, target_features)\n summed = np.sum(multiplied, axis=1)\n return summed\n"
] | [
[
"numpy.sum",
"numpy.multiply",
"pandas.read_csv",
"sklearn.feature_extraction.text.TfidfVectorizer",
"numpy.array"
]
] |
ytirahc/mobile-dev-trek | [
"336602fbc6f91776b6a3e8b845dc2c87d5f4e592"
] | [
"posts/032016/BatchProcessingOpenCV.py"
] | [
"#!/usr/bin/env python\r\n#\r\n# -------------------------------------------------------------------------------------\r\n#\r\n# Copyright (c) 2016, ytirahc, www.mobiledevtrek.com\r\n# All rights reserved. Copyright holder cannot be held liable for any damages. \r\n# \r\n# Distributed under the Apache License (ASL). \r\n# http://www.apache.org/licenses/\r\n# *****\r\n# Description: Python script to resize images by percentage and apply sepia tone effect \r\n# using OpenCV and NumPy (developed with & tested against Python 3.5, OpenCV 3.1 and\r\n# NumPy 1.10.4)\r\n# Resize\r\n# The jpg image files of the specified input directory are resized by the specified percentages\r\n# in the array resizePercentages and saved to the specified output directory. \r\n# Sepia\r\n# The jpg image files of the specified input directory have the sepia tone effect applied and saved \r\n# to the specified output directory.\r\n# \r\n# Usage: Running the script will both resize and apply the sepia tone effect to the jpg images in the\r\n# input directory, saving the results to the output directory\r\n# *****\r\n\r\n\r\n\r\nimport os\r\nimport numpy as np\r\nimport cv2\r\n\r\n\r\n\r\n# *****\r\n# SoftLight\r\n#\r\n# Description: Implements the soft light blending mode as per w3c\r\n# https://en.wikipedia.org/wiki/Blend_modes#Soft_Light\r\n#\r\n# Parameters:\r\n# inTopImg : Open OpenCV image (top)\r\n# inBottomImg : Open OpenCV image (bottom)\r\n# *****\r\ndef SoftLight(inTopImg,inBottomImg):\r\n \r\n # Normalize color values to between 0 and 1\r\n topImgArray = np.asarray(inTopImg) / 255.0\r\n bottomImgArray = np.asarray(inBottomImg) / 255.0\r\n \r\n softLightImgArray = SoftLightF(topImgArray, bottomImgArray)\r\n \r\n # Convert colors back to between 0 to 255\r\n softLightImgArray = softLightImgArray * 255.0\r\n \r\n return softLightImgArray\r\n\r\n\r\n# *****\r\n# SoftLightF\r\n#\r\n# Description: Implements f(bottom image, top image) portion of w3c soft light blending equation\r\n#\r\n# Parameters:\r\n# inTopImgArray : Top image as array\r\n# inBottomImgArray : Bottom image as array\r\n# *****\r\ndef SoftLightF(inTopImgArray,inBottomImgArray):\r\n\r\n softLightFArray = np.where(inTopImgArray <= 0.5,inBottomImgArray - ((1 - (2 * inTopImgArray)) * inBottomImgArray * (1 - inBottomImgArray)),inBottomImgArray + (2 * inTopImgArray - 1) * (SoftLightG(inBottomImgArray) - inBottomImgArray))\r\n\r\n return softLightFArray\r\n\r\n\r\n# *****\r\n# SoftLightG\r\n#\r\n# Description: Implements f(bottom image) portion of w3c soft light blending equation\r\n#\r\n# Parameters:\r\n# inBottomImgArray : Bottom image as array\r\n# *****\r\ndef SoftLightG(inBottomImgArray):\r\n \r\n softLightGArray = np.where(inBottomImgArray <= 0.25, ((16 * inBottomImgArray - 12) * inBottomImgArray + 4) * inBottomImgArray, np.sqrt(inBottomImgArray))\r\n \r\n return softLightGArray\r\n\r\n\r\n# *****\r\n# SepiaToneEffectAndSave\r\n#\r\n# Description: Applies sepia tone effect to input image and saves the result\r\n#\r\n# Parameters:\r\n# inImage : An OpenCV image\r\n# inSepiaImageFN : Output path and file name where the result is saved\r\n# *****\r\ndef SepiaToneEffectAndSave(inImage, inSepiaImageFN):\r\n \r\n # Desaturate (but needs to be RGB for later operations)\r\n imgGrey = cv2.cvtColor(inImage,cv2.COLOR_BGR2GRAY)\r\n imgGrey = cv2.cvtColor(imgGrey,cv2.COLOR_GRAY2RGB) # Need RGB for matrix math\r\n \r\n # Apply a slight blur\r\n imgSmooth = cv2.GaussianBlur(imgGrey,(5,5),0)\r\n\r\n # Blend the sepia tone color with the greyscale layer using soft light\r\n imgWidth, imgHeight, imgChannels = imgGrey.shape\r\n imgSepiaColor = np.zeros((imgWidth,imgHeight,3), np.uint8)\r\n imgSepiaColor[:,:] = (42,89,226) # BGR\r\n \r\n imgSepia = SoftLight(imgSepiaColor, imgSmooth)\r\n \r\n cv2.imwrite(inSepiaImageFN,imgSepia)\r\n\r\n\r\n# *****\r\n# ResizeImageByPercentAndSave\r\n#\r\n# Description: Resizes image by specified percentage and saves the result\r\n#\r\n# Parameters:\r\n# inImage : An OpenCV image\r\n# inResizePercentage : Percentage by which to resize image as a non negative integer\r\n# inResizedImageFN : Output path and file name where the result is saved\r\n# *****\r\ndef ResizeImageByPercentAndSave(inImage, inResizePercentage, inResizedImageFN):\r\n \r\n resizeFraction = inResizePercentage / 100\r\n \r\n imgResize = cv2.resize(inImage, (0,0), fx=resizeFraction, fy=resizeFraction)\r\n \r\n cv2.imwrite(inResizedImageFN,imgResize)\r\n\r\n\r\n\r\nbatchInputImageDir = os.path.join(\"..\",\"images\",\"in\") # Input directory where jpg files reside\r\nbatchOutputImageDir = os.path.join(\"..\",\"images\",\"out\") # Output directory where results are saves as jpg image files\r\nresizePercentages = [75, 50, 25] # Percentages to by which to resize input images\r\n\r\n# Iterate through all jpgs in the input directory \r\nfor jpgFile in os.listdir(batchInputImageDir):\r\n \r\n if jpgFile.endswith(\".jpg\"): # Process jpg files only\r\n \r\n # Determine full path and filename\r\n imageName, imageExt = os.path.splitext(jpgFile)\r\n batchInImageFN = os.path.join(batchInputImageDir, jpgFile)\r\n\r\n print(\"Currently processing image: \" + batchInImageFN)\r\n\r\n # Open the input image to process\r\n img = cv2.imread(batchInImageFN)\r\n \r\n # Resize image by given percentages\r\n for resizePercentage in resizePercentages:\r\n \r\n batchOutImageFN = os.path.join(batchOutputImageDir, imageName + \"_\" + str(resizePercentage) + \".jpg\")\r\n ResizeImageByPercentAndSave(img, resizePercentage, batchOutImageFN)\r\n \r\n # Apply the sepia tone effect\r\n batchOutImageFN = os.path.join(batchOutputImageDir, imageName + \"_sepia.jpg\")\r\n SepiaToneEffectAndSave(img, batchOutImageFN)\r\n \r\nprint(\"Finished processing all jpg images in input directory: \" + batchInputImageDir)\r\nprint(\"Output images files located in the directory: \" + batchOutputImageDir)\r\n"
] | [
[
"numpy.sqrt",
"numpy.asarray",
"numpy.zeros"
]
] |
TU-Berlin-DIMA/ARTC | [
"07f945d1cf976e948c9f2687a8f1a68f79e66c0c"
] | [
"src/udsf/rtta.py"
] | [
"# Contains read interval (diameter) suggestion algorithms\n\nfrom util.PID import PID\nfrom util.pewma import Pewma\n\nfrom math import *\nimport numpy as np\n\n\nclass IntervalSuggestion:\n def __init__(self):\n pass\n\n def next(self, time, value, t_d):\n raise NotImplementedError(\"next(...) not implemented.\")\n\n\nclass Fixed(IntervalSuggestion):\n\n def reset(self): pass\n\n def __init__(self, dur):\n super().__init__()\n assert(dur >= 0)\n self.name = str(list(zip(locals().keys(), locals().values())))\n self.dur = dur\n self.t_s = 0\n self.t_e = 0\n\n def next(self, time, value, t_d):\n self.t_s = max(t_d - self.dur, time + 1)\n self.t_e = max(t_d + self.dur, time + 1)\n\n\nclass ARTC(IntervalSuggestion):\n\n def reset(self):\n self.vLast = float('nan')\n self.pidMean = PID(self.setPoint, self.P, self.I, self.D)\n self.pidVar = PID(self.setPoint, self.P, self.I, self.D)\n self.pewma = Pewma(self.d_init, self.alpha, self.beta)\n self.pewmaDiff = Pewma(self.d_init, self.alpha, self.beta)\n self.ptm = []\n self.pdm = []\n self.pdv = []\n self.ppd = []\n self.pps = []\n\n self.diam = self.minDiam\n self.shift = 0.\n\n def __init__(self, set_point, p_p, p_i, p_d, d_init, alpha, beta, diam_min, diam_max, avg=-1):\n super().__init__()\n self.name = str(list(zip(locals().keys(), locals().values())))\n\n self.setPoint = set_point\n self.P = p_p\n self.I = p_i\n self.D = p_d\n self.d_init = d_init \n self.alpha = alpha\n self.beta = beta\n\n self.minDiam = diam_min\n self.maxDiam = diam_max\n\n self.avg = avg\n\n self.reset()\n\n def __has_sample(self): return not np.isnan(self.vLast).all()\n\n def next(self, t, v, t_d):\n self.pewma.next(np.linalg.norm(v))\n mean = self.pewma.est_mean if self.avg == -1 else self.avg\n\n if self.__has_sample():\n self.pewmaDiff.next(np.linalg.norm(v - self.vLast))\n\n pidn = self.pidMean.next(t, self.pewmaDiff.est_mean / fabs(mean))\n\n if self.pewmaDiff.est_var / mean > self.setPoint:\n self.diam = self.diam * .75\n else:\n self.diam += (self.setPoint - self.pewmaDiff.est_var / mean) / self.setPoint\n \n self.shift = min(max(self.shift + pidn / 10, -.5), .25) \n self.diam = min(max(self.diam, self.minDiam), self.maxDiam)\n\n self.t_s = max(t_d + self.diam * (self.shift - .5), t + 1)\n self.t_e = max(t_d + self.diam * (.5 + self.shift), t + 1)\n \n self.ptm += [t]\n self.pdm += [self.pewmaDiff.est_mean]\n self.pdv += [self.pewmaDiff.est_var]\n self.ppd += [self.diam]\n self.pps += [self.shift]\n\n else:\n self.t_s, self.t_e = max(t_d - 2, t + 1), max(t_d + 1, t + 1)\n self.vLast = v\n\n"
] | [
[
"numpy.linalg.norm",
"numpy.isnan"
]
] |
Brandon-HY-Lin/deep-reinforcement-learning | [
"d809851b6f98d1089379392d4687e2acaf1c0c79"
] | [
"p3_collab-compet/MADDPG/networks/maddpg_critic_version_1.py"
] | [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom networks.network_utils import hidden_init\n\nclass MADDPGCriticVersion1(nn.Module):\n def __init__(self, num_agents, state_size, action_size, fcs1_units, fc2_units, seed=0):\n \"\"\"Initialize parameters and build model.\n Params\n ======\n num_agents (int): number of agents\n state_size (int): Dimension of each state\n action_size (int): Dimension of each action\n seed (int): Random seed\n fcs1_units (int): Number of nodes in the first hidden layer\n fc2_units (int): Number of nodes in the second hidden layer\n \"\"\"\n super().__init__()\n \n self.seed = torch.manual_seed(seed)\n self.fcs1 = nn.Linear(num_agents*state_size, fcs1_units)\n self.fc2 = nn.Linear(fcs1_units+(num_agents*action_size), fc2_units)\n self.fc3 = nn.Linear(fc2_units, 1)\n \n self.reset_parameters()\n \n def reset_parameters(self):\n self.fcs1.weight.data.uniform_(*hidden_init(self.fcs1))\n self.fc2.weight.data.uniform_(*hidden_init(self.fc2))\n self.fc3.weight.data.uniform_(-3e-3, 3e-3)\n \n \n def forward(self, states_1d, actions_1d):\n \"\"\"\n Build a critic (value) network that maps (state, action) pairs -> Q-values.\n \n Args:\n states_1d (torch.tensor): shape[1] = (num_agents*state_size)\n actions_1d (torch.tensor): shape[1] = (num_agents*action_size)\n \"\"\"\n xs = F.relu(self.fcs1(states_1d))\n x = torch.cat((xs, actions_1d), dim=1)\n x = F.relu(self.fc2(x))\n \n return self.fc3(x)\n"
] | [
[
"torch.manual_seed",
"torch.nn.Linear",
"torch.cat"
]
] |
shahrukhx01/nnti_hindi_bengali_sentiment_analysis | [
"94cd0c335e5ff592a2b09f95adc183dac2b54d9f"
] | [
"src/task3/1_hindi_bengali_bilstm_sa_jdil/bengali_data.py"
] | [
"import pandas as pd\nimport numpy as np\nfrom bengali_preprocess import Preprocess\nimport logging\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data.sampler import SubsetRandomSampler\nfrom bengali_dataset import BengaliDataset\nlogging.basicConfig(level=logging.INFO)\n\n\"\"\"\nFor loading Bengali data loading and preprocessing\n\"\"\"\nclass BengaliData:\n def __init__(self, file_path):\n \"\"\"\n Loads data into memory and create vocabulary from text field.\n \"\"\"\n self.load_data(file_path) ## load data file into memory\n self.create_vocab() ## create vocabulary over entire dataset before train/test split\n \n def load_data(self, file_paths):\n \"\"\"\n Reads data set file from disk to memory using pandas\n \"\"\"\n logging.info('loading and preprocessing data...')\n self.data = pd.read_csv(file_paths['data_file']) ## reading data file\n self.data = Preprocess(file_paths['stpwds_file']).perform_preprocessing(self.data) ## performing text preprocessing\n logging.info('reading and preprocessing data completed...')\n \n def create_vocab(self):\n \"\"\"\n Creates vocabulary over entire text data field.\n \"\"\"\n logging.info('creating vocabulary...')\n self.vocab = sorted(list(self.data.clean_text.str.split(expand=True).stack().value_counts().keys()))\n self.word2index = {word:index for index,word in enumerate(self.vocab)} ## map each word to index\n self.index2word = {index:word for index,word in enumerate(self.vocab)} ## map each index to word\n logging.info('creating vocabulary completed...')\n\n def transform_labels(self):\n \"\"\"\n Maps categorical string labels to {0, 1}\n \"\"\"\n self.data.rename(columns={\"hate\": \"labels\"}, inplace=True) ## rename target column\n \n\n def data2tensors(self):\n \"\"\"\n Converts raw data sequences into vectorized sequences as tensors\n \"\"\"\n self.transform_labels()\n vectorized_sequences, sequence_lengths, targets = [], [], []\n raw_data = list(self.data.clean_text.values)\n\n ## get the text sequence from dataframe\n for index, sentence in enumerate(raw_data):\n ## convert sentence into vectorized form replacing words with vocab indices\n vectorized_sequence = self.vectorize_sequence(sentence)\n sequence_length = len(vectorized_sequence) ## computing sequence lengths for padding\n if sequence_length <= 0:\n continue\n \n vectorized_sequences.append(vectorized_sequence) ## adding sequence vectors to train matrix \n sequence_lengths.append(sequence_length) \n targets.append(self.data.labels.values[index]) ## fetching label for this example\n \n ## padding zeros at the end of tensor till max length tensor\n padded_sequence_tensor = self.pad_sequences(vectorized_sequences, torch.LongTensor(sequence_lengths))\n length_tensor = torch.LongTensor(sequence_lengths) ## casting to long \n target_tensor = torch.LongTensor(targets) ## casting to long \n\n return (padded_sequence_tensor, target_tensor, length_tensor, raw_data )\n\n\n def get_data_loader(self, batch_size = 8):\n padded_sequence_tensor, target_tensor, length_tensor, raw_data = self.data2tensors()\n self.bengali_dataset = BengaliDataset(padded_sequence_tensor, target_tensor, length_tensor, raw_data)\n \n train_sampler, dev_sampler, test_sampler = self.train_dev_test_split()\n ## prepare dictionary for train and test PyTorch based dataloaders\n bengali_dataloader = {'train_loader' : torch.utils.data.DataLoader(self.bengali_dataset, batch_size=batch_size, \n sampler=train_sampler),\n 'test_loader' : torch.utils.data.DataLoader(self.bengali_dataset, batch_size=batch_size,\n sampler=test_sampler),\n 'dev_loader' : torch.utils.data.DataLoader(self.bengali_dataset, batch_size=batch_size,\n sampler=dev_sampler)}\n return bengali_dataloader\n\n def train_dev_test_split(self, dev_size= 0.2, test_size= 0.2, shuffle_dataset= True, random_seed=42):\n \"\"\"\n Splits the data into train and test set using the SubsetSampler provided by PyTorch.\n \"\"\"\n ## creating data indices for training and validation splits:\n dataset_size = len(self.bengali_dataset)\n indices = list(range(dataset_size))\n train_test_split = int(np.floor(test_size * dataset_size))\n if shuffle_dataset :\n np.random.seed(random_seed)\n np.random.shuffle(indices) ## shuffle row indices before split\n train_indices, test_indices = indices[train_test_split:], indices[:train_test_split]\n \n train_dev_split = int(np.floor(dev_size * len(train_indices))) ## splitting train data further into train and dev\n train_indices, dev_indices = train_indices[train_dev_split:], train_indices[:train_dev_split]\n\n ## creating pytorch data samplers \n return SubsetRandomSampler(train_indices), SubsetRandomSampler(dev_indices), SubsetRandomSampler(test_indices)\n\n def sort_batch(self, batch, targets, lengths):\n \"\"\"\n Sorts the data, lengths and target tensors based on the lengths \n of the sequences from longest to shortest in batch\n \"\"\"\n sequence_lengths, perm_idx = lengths.sort(0, descending=True)\n sequence_tensor = batch[perm_idx]\n target_tensor = targets[perm_idx]\n return sequence_tensor.transpose(0, 1), target_tensor, sequence_lengths\n\n def vectorize_sequence(self, sentence):\n \"\"\"\n Replaces tokens with their indices in vocabulary\n \"\"\"\n return [self.word2index[token] for token in sentence.split()]\n \n def pad_sequences(self, vectorized_sequences, sequence_lengths):\n \"\"\" \n Pads zeros at the end of each sequence in data tensor till max \n length of sequence in that batch\n \"\"\"\n padded_sequence_tensor = torch.zeros((len(vectorized_sequences), sequence_lengths.max())).long() ## init zeros tensor\n for idx, (seq, seqlen) in enumerate(zip(vectorized_sequences, sequence_lengths)): ## iterate over each sequence\n padded_sequence_tensor[idx, :seqlen] = torch.LongTensor(seq) ## each sequence get padded by zeros until max length in that batch\n return padded_sequence_tensor ## returns padded tensor\n "
] | [
[
"torch.utils.data.DataLoader",
"numpy.random.shuffle",
"pandas.read_csv",
"numpy.floor",
"numpy.random.seed",
"torch.utils.data.sampler.SubsetRandomSampler",
"torch.LongTensor"
]
] |
YangYunjia/cst-modeling3d | [
"4d997015afd12b9b049f21c4b6c3c350e9f6a91c"
] | [
"cst_modeling/foil.py"
] | [
"'''\r\nThis is a module containing functions to construct an airfoil\r\n'''\r\nimport copy\r\n\r\nimport numpy as np\r\nfrom numpy.linalg import lstsq\r\nfrom scipy import spatial\r\nfrom scipy.interpolate import interp1d\r\nfrom scipy.special import factorial\r\n\r\nfrom .naca import naca\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nclass BasicSection():\r\n '''\r\n Section: 3D curve and 2D unit curve\r\n '''\r\n def __init__(self, thick=None, chord=1.0, twist=0.0):\r\n self.xLE = 0.0\r\n self.yLE = 0.0\r\n self.zLE = 0.0\r\n self.chord = chord\r\n self.twist = twist\r\n self.thick = 0.0\r\n self.thick_set = thick\r\n\r\n #* 2D unit curve\r\n self.xx = None\r\n self.yy = None # open curve\r\n self.yu = None # upper surface of closed curve\r\n self.yl = None # lower surface of closed curve\r\n\r\n #* 3D section\r\n self.x = np.zeros(1)\r\n self.y = np.zeros(1)\r\n self.z = np.zeros(1)\r\n\r\n def set_params(self, init=False, **kwargs):\r\n '''\r\n Set parameters of the section\r\n\r\n ### Inputs:\r\n ```text\r\n init: True, set to default values\r\n ```\r\n\r\n ### kwargs:\r\n ```text\r\n xLE, yLE, zLE, chord, twist, thick (None)\r\n ```\r\n '''\r\n if init:\r\n self.xLE = 0.0\r\n self.yLE = 0.0\r\n self.zLE = 0.0\r\n self.chord = 1.0\r\n self.twist = 0.0\r\n self.thick = 0.0\r\n self.thick_set = None\r\n\r\n return\r\n\r\n if 'xLE' in kwargs.keys():\r\n self.xLE = kwargs['xLE']\r\n\r\n if 'yLE' in kwargs.keys():\r\n self.yLE = kwargs['yLE']\r\n\r\n if 'zLE' in kwargs.keys():\r\n self.zLE = kwargs['zLE']\r\n\r\n if 'chord' in kwargs.keys():\r\n self.chord = kwargs['chord']\r\n\r\n if 'twist' in kwargs.keys():\r\n self.twist = kwargs['twist']\r\n\r\n if 'thick' in kwargs.keys():\r\n self.thick_set = kwargs['thick']\r\n\r\n def section(self, nn=1001, flip_x=False, proj=True):\r\n '''\r\n ### Functions:\r\n ```text\r\n 1. Construct 2D unit curve (null in the BasicSection)\r\n 2. Transform to 3D curve\r\n ```\r\n\r\n ### Inputs:\r\n ```text\r\n nn: total amount of points (it's here for function BasicSurface.geo_secs)\r\n flip_x: True ~ flip section.xx in reverse order\r\n proj: True => for unit airfoil, the rotation keeps the projection length the same\r\n ```\r\n '''\r\n if not isinstance(self.xx, np.ndarray):\r\n raise Exception('The 2D curve has not been constructed')\r\n\r\n #* Flip xx\r\n if flip_x:\r\n self.xx = np.flip(self.xx)\r\n\r\n #* Transform to 3D for open section\r\n if isinstance(self.yy, np.ndarray):\r\n self.x, _, self.y, _ = transform(self.xx, self.xx, self.yy, self.yy, \r\n scale=self.chord, rot=self.twist, dx=self.xLE, dy=self.yLE, proj=proj)\r\n\r\n self.z = np.ones_like(self.x)*self.zLE\r\n\r\n #* Transform to 3D for closed section\r\n if isinstance(self.yu, np.ndarray):\r\n xu_, xl_, yu_, yl_ = transform(self.xx, self.xx, self.yu, self.yl, \r\n scale=self.chord, rot=self.twist, dx=self.xLE, dy=self.yLE, proj=proj)\r\n\r\n self.x = np.concatenate((np.flip(xl_),xu_[1:]), axis=0)\r\n self.y = np.concatenate((np.flip(yl_),yu_[1:]), axis=0)\r\n self.z = np.ones_like(self.x)*self.zLE\r\n\r\n def copyfrom(self, other):\r\n '''\r\n Copy from anthor BasicSection object\r\n '''\r\n if not isinstance(other, BasicSection):\r\n raise Exception('Must copy from another BasicSection object')\r\n \r\n self.xLE = other.xLE\r\n self.yLE = other.yLE\r\n self.zLE = other.zLE\r\n self.chord = other.chord\r\n self.twist = other.twist\r\n\r\n self.xx = copy.deepcopy(other.xx)\r\n self.yy = copy.deepcopy(other.yy)\r\n self.yu = copy.deepcopy(other.yu)\r\n self.yl = copy.deepcopy(other.yl)\r\n\r\n self.x = other.x.copy()\r\n self.y = other.y.copy()\r\n self.z = other.z.copy()\r\n\r\n\r\nclass Section(BasicSection):\r\n '''\r\n Section 3D curve generated by CST foil (upper & lower surface)\r\n '''\r\n def __init__(self, thick=None, chord=1.0, twist=0.0, tail=0.0):\r\n\r\n super().__init__(thick=thick, chord=chord, twist=twist)\r\n\r\n self.tail = tail\r\n self.RLE = 0.0\r\n\r\n #* 2D unit airfoil\r\n self.cst_u = np.zeros(1)\r\n self.cst_l = np.zeros(1)\r\n\r\n #* Refine airfoil\r\n self.refine_u = None\r\n self.refine_l = None\r\n\r\n #* Round tail\r\n self.cst_flip_u = None\r\n self.cst_flip_l = None\r\n\r\n def set_params(self, init=False, **kwargs):\r\n '''\r\n Set parameters of the section\r\n\r\n ### Inputs:\r\n ```text\r\n init: True, set to default values\r\n ```\r\n\r\n ### kwargs:\r\n ```text\r\n xLE, yLE, zLE, chord, twist, tail, thick (None)\r\n\r\n refine_u: ndarray, cst coefficients of upper incremental curve\r\n refine_l: ndarray, cst coefficients of lower incremental curve\r\n\r\n cst_flip_u: ndarray, cst coefficients of upper flipped incremental curve\r\n cst_flip_l: ndarray, cst coefficients of lower flipped incremental curve\r\n ```\r\n '''\r\n if init:\r\n super().set_params(init=True)\r\n\r\n self.tail = 0.0\r\n self.RLE = 0.0\r\n\r\n self.refine_u = None\r\n self.refine_l = None\r\n return\r\n\r\n super().set_params(init=False, **kwargs)\r\n\r\n if 'tail' in kwargs.keys():\r\n self.tail = kwargs['tail']\r\n\r\n if 'refine_u' in kwargs.keys():\r\n aa_ = kwargs['refine_u']\r\n if isinstance(aa_, np.ndarray):\r\n self.refine_u = aa_.copy()\r\n\r\n if 'refine_l' in kwargs.keys():\r\n aa_ = kwargs['refine_l']\r\n if isinstance(aa_, np.ndarray):\r\n self.refine_l = aa_.copy()\r\n\r\n if 'cst_flip_u' in kwargs.keys():\r\n aa_ = kwargs['cst_flip_u']\r\n if isinstance(aa_, np.ndarray):\r\n self.cst_flip_u = aa_.copy()\r\n\r\n if 'cst_flip_l' in kwargs.keys():\r\n aa_ = kwargs['cst_flip_l']\r\n if isinstance(aa_, np.ndarray):\r\n self.cst_flip_l = aa_.copy()\r\n\r\n def section(self, cst_u=None, cst_l=None, nn=1001, flip_x=False, proj=True):\r\n '''\r\n Generating the section (3D) by cst_foil. \r\n\r\n ### Functions:\r\n ```text\r\n 1. Construct 2D unit curve (null in the BasicSection)\r\n 2. Transform to 3D curve\r\n ```\r\n\r\n ### Inputs:\r\n ```text\r\n nn: total amount of points\r\n cst_u: CST coefficients of upper surface (ndarray, optional)\r\n cst_l: CST coefficients of lower surface (ndarray, optional)\r\n flip_x: True ~ flip section.xx in reverse order\r\n proj: True => for unit airfoil, the rotation keeps the projection length the same\r\n ```\r\n '''\r\n #* Update CST parameters\r\n if isinstance(cst_u, np.ndarray) and isinstance(cst_l, np.ndarray):\r\n self.cst_u = cst_u.copy()\r\n self.cst_l = cst_l.copy()\r\n\r\n #* Construct airfoil with CST parameters\r\n self.xx, self.yu, self.yl, self.thick, self.RLE = cst_foil(\r\n nn, self.cst_u, self.cst_l, t=self.thick_set, tail=self.tail)\r\n\r\n #* Refine the airfoil by incremental curves\r\n yu_i = np.zeros(nn)\r\n yl_i = np.zeros(nn)\r\n\r\n if isinstance(self.refine_u, np.ndarray):\r\n _, y_tmp = cst_curve(nn, self.refine_u, x=self.xx)\r\n yu_i += y_tmp\r\n\r\n if isinstance(self.refine_l, np.ndarray):\r\n _, y_tmp = cst_curve(nn, self.refine_l, x=self.xx)\r\n yl_i += y_tmp\r\n\r\n #* Add round tail with incremental curves\r\n if isinstance(self.cst_flip_u, np.ndarray):\r\n _, y_tmp = cst_curve(nn, self.cst_flip_u, x=1.0-self.xx)\r\n yu_i += y_tmp\r\n\r\n if isinstance(self.cst_flip_l, np.ndarray):\r\n _, y_tmp = cst_curve(nn, self.cst_flip_l, x=1.0-self.xx)\r\n yl_i += y_tmp\r\n\r\n self.yu, self.yl = foil_increment_curve(self.xx, self.yu, self.yl, yu_i=yu_i, yl_i=yl_i, t=self.thick_set)\r\n\r\n #* Transform to 3D\r\n super().section(flip_x=flip_x, proj=proj)\r\n\r\n def copyfrom(self, other):\r\n '''\r\n Copy from anthor section object\r\n '''\r\n if not isinstance(other, Section):\r\n raise Exception('Must copy from another section object')\r\n \r\n super().copyfrom(other)\r\n\r\n self.tail = other.tail\r\n self.RLE = other.RLE\r\n\r\n self.cst_u = other.cst_u.copy()\r\n self.cst_l = other.cst_l.copy()\r\n\r\n self.refine_u = copy.deepcopy(other.refine_u)\r\n self.refine_l = copy.deepcopy(other.refine_l)\r\n self.cst_flip_u = copy.deepcopy(other.cst_flip_u)\r\n self.cst_flip_l = copy.deepcopy(other.cst_flip_l)\r\n\r\n\r\nclass OpenSection(BasicSection):\r\n '''\r\n Section 3D curve generated by CST curve (open curve)\r\n '''\r\n def __init__(self, thick=None, chord=1.0, twist=0.0):\r\n\r\n super().__init__(thick=thick, chord=chord, twist=twist)\r\n\r\n #* 2D unit curve\r\n self.cst = np.zeros(1)\r\n\r\n #* Refine airfoil\r\n self.refine = None\r\n\r\n #* Round tail\r\n self.cst_flip = None\r\n\r\n def set_params(self, init=False, **kwargs):\r\n '''\r\n Set parameters of the section\r\n\r\n ### Inputs:\r\n ```text\r\n init: True, set to default values\r\n ```\r\n\r\n ### kwargs:\r\n ```text\r\n xLE, yLE, zLE, chord, twist, thick (None)\r\n refine: ndarray, cst coefficients of incremental curve\r\n cst_flip: ndarray, cst coefficients of flipped incremental curve\r\n ```\r\n '''\r\n if init:\r\n super().set_params(init=True)\r\n \r\n self.refine = None\r\n return\r\n \r\n super().set_params(init=False, **kwargs)\r\n\r\n if 'refine' in kwargs.keys():\r\n aa_ = kwargs['refine']\r\n if isinstance(aa_, np.ndarray):\r\n self.refine = aa_.copy()\r\n\r\n if 'cst_flip' in kwargs.keys():\r\n aa_ = kwargs['cst_flip']\r\n if isinstance(aa_, np.ndarray):\r\n self.cst_flip = aa_.copy()\r\n\r\n def section(self, cst=None, nn=1001, flip_x=False, proj=True):\r\n '''\r\n Generating the section (3D) by cst_curve. \r\n\r\n ### Functions:\r\n ```text\r\n 1. Construct 2D unit curve (null in the BasicSection)\r\n 2. Transform to 3D curve\r\n ```\r\n\r\n ### Inputs:\r\n ```text\r\n nn: total amount of points\r\n cst: CST coefficients of the curve (ndarray, optional)\r\n flip_x: True ~ flip section.xx in reverse order\r\n proj: True => for unit airfoil, the rotation keeps the projection length the same\r\n ```\r\n '''\r\n #* Update CST parameters\r\n if isinstance(cst, np.ndarray):\r\n self.cst = cst.copy()\r\n\r\n #* Construct curve with CST parameters\r\n self.xx, self.yy = cst_curve(nn, self.cst)\r\n\r\n #* Refine the geometry with an incremental curve\r\n if isinstance(self.refine, np.ndarray):\r\n _, y_i = cst_curve(nn, self.refine, x=self.xx)\r\n self.yy += y_i\r\n\r\n #* Add round tail with an incremental curve\r\n if isinstance(self.cst_flip, np.ndarray):\r\n _, y_i = cst_curve(nn, self.cst_flip, x=1.0-self.xx)\r\n self.yy += y_i\r\n\r\n #* Apply thickness\r\n self.thick = np.max(self.yy, axis=0)\r\n if isinstance(self.thick_set, float):\r\n self.yy = self.yy/self.thick*self.thick_set\r\n self.thick = self.thick_set\r\n\r\n #* Transform to 3D\r\n super().section(flip_x=flip_x, proj=proj)\r\n\r\n def copyfrom(self, other):\r\n '''\r\n Copy from anthor OpenSection object\r\n '''\r\n if not isinstance(other, OpenSection):\r\n raise Exception('Must copy from another OpenSection object')\r\n\r\n super().copyfrom(other)\r\n\r\n self.cst = other.cst.copy()\r\n\r\n self.refine = copy.deepcopy(other.refine)\r\n self.cst_flip = copy.deepcopy(other.cst_flip)\r\n\r\n\r\n#* ===========================================\r\n#* Static functions\r\n#* ===========================================\r\n\r\ndef cst_foil(nn, coef_upp, coef_low, x=None, t=None, tail=0.0):\r\n '''\r\n Constructing upper and lower curves of an airfoil based on CST method\r\n\r\n CST: class shape transfermation method (Kulfan, 2008)\r\n\r\n >>> x_, yu, yl, t0, R0 = cst_foil()\r\n\r\n ### Inputs:\r\n ```text\r\n nn: total amount of points\r\n coef_upp: CST coefficients of upper surface (ndarray)\r\n coef_low: CST coefficients of lower surface (ndarray)\r\n x: point x [0,1] (optional ndarray, size is nn)\r\n t: relative maximum thickness (optional)\r\n tail: relative tail thickness (optional)\r\n ```\r\n\r\n ### Return\r\n x (ndarray), y_upp (ndarray), y_low (ndarray), t0, R0\r\n '''\r\n x_, yu = cst_curve(nn, coef_upp, x=x)\r\n x_, yl = cst_curve(nn, coef_low, x=x)\r\n \r\n yu, yl, t_max= set_t_tail(x_, yu, x_, yl, tail, t_max=t)\r\n\r\n # Calculate leading edge radius\r\n x_RLE = 0.005\r\n yu_RLE = interplot_from_curve(x_RLE, x_, yu)\r\n yl_RLE = interplot_from_curve(x_RLE, x_, yl)\r\n R0, _ = find_circle_3p([0.0,0.0], [x_RLE,yu_RLE], [x_RLE,yl_RLE])\r\n\r\n return x_, yu, yl, t_max, R0\r\n\r\ndef set_t_tail(xu_, yu_, xl_, yl_, t_tail, t_max = None):\r\n xu = np.array(xu_)\r\n yu = np.array(yu_)\r\n xl = np.array(xl_)\r\n yl = np.array(yl_)\r\n \r\n \r\n # yu = copy.deepcopy(yu_)\r\n # yl = copy.deepcopy(yl_)\r\n\r\n # if need to set thick to a specific number, xu and xl should be aligned\r\n # otherwise only need to align the tail point([-1])\r\n if t_max is not None:\r\n thick = yu - yl\r\n t_max_idx = np.argmax(thick)\r\n t_max_0 = thick[t_max_idx]\r\n \r\n if abs(xu[-1] - xl[-1]) > 1e-3:\r\n raise Exception(\"xu and xl not aligned\")\r\n\r\n t_tail_0 = yu[-1] - yl[-1]\r\n \r\n print(f'T_tail {t_tail_0} -> {t_tail}')\r\n\r\n # Apply thickness constraint\r\n if t_max is not None:\r\n ratio = (t_max - (t_tail - t_tail_0) * xu[t_max_idx]) / t_max_0\r\n yu = yu * ratio\r\n yl = yl * ratio\r\n\r\n # Add tail\r\n yu += 0.5 * (t_tail - t_tail_0) * xu\r\n yl -= 0.5 * (t_tail - t_tail_0) * xl\r\n \r\n return yu, yl, t_max\r\n\r\n\r\ndef cst_foil_fit(xu, yu, xl, yl, n_cst=7):\r\n '''\r\n Using CST method to fit an airfoil\r\n\r\n This function allows the airfoil has non-zero tail thickness.\r\n Also allows the airfoil chord length not equals to one.\r\n\r\n >>> cst_u, cst_l = cst_foil_fit(xu, yu, xl, yl, n_cst=7)\r\n\r\n ### Inputs:\r\n ```text\r\n xu, yu: upper surface points (ndarray)\r\n xl, yl: lower surface points (ndarray)\r\n n_cst: number of CST parameters\r\n ```\r\n\r\n ### Return: \r\n cst_u, cst_l (ndarray)\r\n '''\r\n cst_u = fit_curve(xu, yu, n_cst=n_cst)\r\n cst_l = fit_curve(xl, yl, n_cst=n_cst)\r\n return cst_u, cst_l\r\n\r\ndef foil_bump_modify(x: np.array, yu: np.array, yl: np.array,\r\n xc: float, h: float, s: float, side=1, n_order=0,\r\n return_cst=False, keep_tmax=True):\r\n '''\r\n Add bumps on the airfoil\r\n\r\n >>> yu_new, yl_new (, cst_u, cst_l) = foil_bump_modify(\r\n >>> x: np.array, yu: np.array, yl: np.array, \r\n >>> xc: float, h: float, s: float, side=1,\r\n >>> n_order=0, return_cst=False, keep_tmax=True)\r\n\r\n ### Inputs:\r\n ```text\r\n x, yu, yl: current airfoil (ndarray)\r\n xc: x of the bump center\r\n h: relative height of the bump (to maximum thickness)\r\n s: span of the bump\r\n side: +1/-1 upper/lower side of the airfoil\r\n n_order: if specified (>0), then use CST to fit the new foil\r\n return_cst: if True, also return cst_u, cst_l when n_order > 0\r\n keep_tmax: if True, keep the maximum thickness unchanged\r\n ```\r\n\r\n ### Return:\r\n yu_new, yl_new (ndarray)\r\n '''\r\n yu_new = yu.copy()\r\n yl_new = yl.copy()\r\n t0 = np.max(yu_new-yl_new)\r\n\r\n yu_ = yu.copy()\r\n yl_ = yl.copy()\r\n\r\n if xc<0.1 or xc>0.9:\r\n kind = 'H'\r\n else:\r\n kind = 'G'\r\n\r\n if side > 0:\r\n yu_new = add_bump(x, yu_new, xc, h*t0, s, kind=kind)\r\n else:\r\n yl_new = add_bump(x, yl_new, xc, h*t0, s, kind=kind)\r\n\r\n if keep_tmax:\r\n\r\n it = np.argmax(yu_new-yl_new)\r\n tu = np.abs(yu_new[it])\r\n tl = np.abs(yl_new[it])\r\n\r\n if side > 0:\r\n rl = (t0-tu)/tl\r\n yl_new = rl * np.array(yl_new)\r\n else:\r\n ru = (t0-tl)/tu\r\n yu_new = ru * np.array(yu_new)\r\n\r\n t0 = None\r\n\r\n if n_order > 0:\r\n # CST reverse\r\n tail = yu[-1] - yl[-1]\r\n cst_u, cst_l = cst_foil_fit(x, yu_new, x, yl_new, n_order=n_order)\r\n _, yu_new, yl_new, _, _ = cst_foil(x.shape[0], cst_u, cst_l, x=x, t=t0, tail=tail)\r\n else:\r\n cst_u = None\r\n cst_l = None\r\n \r\n if return_cst:\r\n return yu_new, yl_new, cst_u, cst_l\r\n else:\r\n return yu_new, yl_new\r\n\r\ndef foil_tcc(x, yu, yl, info=True):\r\n '''\r\n Calculate thickness, curvature, camber distribution.\r\n\r\n >>> thickness, curv_u, curv_l, camber = foil_tcc(x, yu, yl, info=True)\r\n\r\n ### Inputs:\r\n ```text\r\n x, yu, yl: current airfoil (ndarray)\r\n ```\r\n\r\n ### Return: \r\n thickness, curv_u, curv_l, camber (ndarray)\r\n '''\r\n curv_u = curve_curvature(x, yu)\r\n curv_l = curve_curvature(x, yl)\r\n\r\n thickness = yu-yl\r\n camber = 0.5*(yu+yl)\r\n for i in range(x.shape[0]):\r\n if info and thickness[i]<0:\r\n print('Unreasonable Airfoil: negative thickness')\r\n\r\n return thickness, curv_u, curv_l, camber\r\n\r\ndef check_valid(x, yu, yl, RLE=0.0, neg_tcri=0.0) -> list:\r\n '''\r\n Check if the airfoil is reasonable by rules\r\n\r\n >>> rule_invalid = check_valid(x, yu, yl, RLE=0.0)\r\n\r\n ### Inputs:\r\n ```text\r\n x, yu, yl: current airfoil (ndarray)\r\n RLE: The leading edge radius of this airfoil\r\n neg_tcri: critical value for checking negative thickness\r\n e.g., neg_tcri = -0.01, then only invalid when the thickness is smaller than -0.01\r\n ```\r\n\r\n ### Rules:\r\n ```text\r\n 1: negative thickness\r\n 2: maximum thickness point location\r\n 3: extreme points of thickness\r\n 4: maximum curvature\r\n 5: maximum camber within x [0.2,0.7]\r\n 6: RLE if provided\r\n 7: convex LE\r\n ```\r\n\r\n ### Return:\r\n rule_invalid: list, 0 means valid\r\n '''\r\n thickness, curv_u, curv_l, camber = foil_tcc(x, yu, yl, info=False)\r\n nn = x.shape[0]\r\n\r\n n_rule = 10\r\n rule_invalid = [0 for _ in range(n_rule)]\r\n\r\n #* Rule 1: negative thickness\r\n if np.min(thickness) < neg_tcri:\r\n rule_invalid[0] = 1\r\n\r\n #* Rule 2: maximum thickness point location\r\n i_max = np.argmax(thickness)\r\n t0 = thickness[i_max]\r\n x_max = x[i_max]\r\n if x_max<0.15 or x_max>0.75:\r\n rule_invalid[1] = 1\r\n\r\n #* Rule 3: extreme points of thickness\r\n n_extreme = 0\r\n for i in range(nn-2):\r\n a1 = thickness[i+2]-thickness[i+1]\r\n a2 = thickness[i]-thickness[i+1]\r\n if a1*a2>=0.0:\r\n n_extreme += 1\r\n if n_extreme>2:\r\n rule_invalid[2] = 1\r\n\r\n #* Rule 4: maximum curvature\r\n cur_max_u = 0.0\r\n cur_max_l = 0.0\r\n for i in range(nn):\r\n if x[i]<0.1:\r\n continue\r\n cur_max_u = max(cur_max_u, abs(curv_u[i]))\r\n cur_max_l = max(cur_max_l, abs(curv_l[i]))\r\n\r\n if cur_max_u>5 or cur_max_l>5:\r\n rule_invalid[3] = 1\r\n\r\n #* Rule 5: Maximum camber within x [0.2,0.7]\r\n cam_max = 0.0\r\n for i in range(nn):\r\n if x[i]<0.2 or x[i]>0.7:\r\n continue\r\n cam_max = max(cam_max, abs(camber[i]))\r\n\r\n if cam_max>0.025:\r\n rule_invalid[4] = 1\r\n \r\n #* Rule 6: RLE\r\n if RLE>0.0 and RLE<0.005:\r\n rule_invalid[5] = 1\r\n\r\n if RLE>0.0 and RLE/t0<0.01:\r\n rule_invalid[5] = 1\r\n\r\n #* Rule 7: convex LE\r\n ii = int(0.1*nn)+1\r\n a0 = thickness[i_max]/x[i_max]\r\n au = yu[ii]/x[ii]/a0\r\n al = -yl[ii]/x[ii]/a0\r\n\r\n if au<1.0 or al<1.0:\r\n rule_invalid[6] = 1\r\n \r\n #if sum(rule_invalid)<=0:\r\n # np.set_printoptions(formatter={'float': '{: 0.6f}'.format}, linewidth=100)\r\n # print(np.array([x_max, n_extreme, cur_max_u, cur_max_l, cam_max, RLE/t0, au, al]))\r\n\r\n return rule_invalid\r\n\r\ndef foil_increment(x, yu, yl, coef_upp, coef_low, t=None):\r\n '''\r\n Add cst curve by incremental curves\r\n\r\n >>> yu_, yl_ = foil_increment(x, yu, yl, coef_upp, coef_low, t=None)\r\n\r\n ### Inputs:\r\n ```text\r\n x, yu, yl: baseline airfoil (ndarray)\r\n coef_upp: CST coefficients of incremental upper curve (ndarray or None)\r\n coef_low: CST coefficients of incremental lower curve (ndarray or None)\r\n t: relative maximum thickness (optional)\r\n ```\r\n\r\n ### Return: \r\n y_upp, y_low (ndarray)\r\n '''\r\n nn = len(x)\r\n\r\n if coef_upp is not None:\r\n _, yu_i = cst_curve(nn, coef_upp, x=x)\r\n else:\r\n yu_i = None\r\n\r\n if coef_upp is not None:\r\n _, yl_i = cst_curve(nn, coef_low, x=x)\r\n else:\r\n yl_i = None\r\n\r\n yu_, yl_ = foil_increment_curve(x, yu, yl, yu_i=yu_i, yl_i=yl_i, t=t)\r\n\r\n return yu_, yl_\r\n\r\ndef foil_increment_curve(x, yu, yl, yu_i=None, yl_i=None, t=None):\r\n '''\r\n Add cst curve by incremental curves\r\n\r\n >>> yu_, yl_ = foil_increment_curve(x, yu, yl, yu_i, yl_i, t=None)\r\n\r\n ### Inputs:\r\n ```text\r\n x, yu, yl: baseline airfoil (ndarray)\r\n yu_i, yl_i: incremental curves (ndarray)\r\n t: relative maximum thickness (optional)\r\n ```\r\n\r\n ### Return: \r\n yu_, yl_ (ndarray)\r\n '''\r\n nn = len(x)\r\n\r\n if not isinstance(yu_i, np.ndarray):\r\n yu_i = np.zeros(nn)\r\n\r\n if not isinstance(yl_i, np.ndarray):\r\n yl_i = np.zeros(nn)\r\n\r\n x_ = x.copy()\r\n yu_ = yu.copy()\r\n yl_ = yl.copy()\r\n\r\n # Remove tail\r\n tail = yu_[-1] - yl_[-1]\r\n if tail > 0.0:\r\n yu_ = yu_ - 0.5*tail*x_\r\n yl_ = yl_ + 0.5*tail*x_\r\n\r\n # Add incremental curves\r\n yu_ = yu_ + yu_i\r\n yl_ = yl_ + yl_i\r\n\r\n thick = yu_-yl_\r\n it = np.argmax(thick)\r\n t0 = thick[it]\r\n\r\n # Apply thickness constraint\r\n if t is not None:\r\n r = (t-tail*x[it])/t0\r\n yu_ = yu_ * r\r\n yl_ = yl_ * r\r\n\r\n # Add tail\r\n if tail > 0.0:\r\n yu_ = yu_ + 0.5*tail*x_\r\n yl_ = yl_ - 0.5*tail*x_\r\n\r\n return yu_, yl_\r\n\r\ndef naca_to_cst(NACA_series: str, n_order=7, nn=101):\r\n '''\r\n Get CST parameters of a NACA series airfoil\r\n\r\n >>> cst_u, cst_l = naca_to_cst(NACA_series, n_order, nn)\r\n\r\n ### Inputs:\r\n ```text\r\n NACA_series: 4 or 5 digit NACA number string\r\n n_order: number of CST parameters\r\n nn: total amount of points\r\n ```\r\n\r\n ### Return: \r\n cst_u, cst_l (ndarray)\r\n '''\r\n xx, yy = naca(NACA_series, nn-1, finite_TE=False, half_cosine_spacing=True)\r\n\r\n xu = np.zeros(nn)\r\n xl = np.zeros(nn)\r\n yu = np.zeros(nn)\r\n yl = np.zeros(nn)\r\n\r\n n0 = 2*nn-1\r\n for i in range(nn):\r\n xu[i] = xx[n0-i-nn]\r\n yu[i] = yy[n0-i-nn]\r\n xl[i] = xx[nn+i-1]\r\n yl[i] = yy[nn+i-1]\r\n\r\n cst_u, cst_l = cst_foil_fit(xu, yu, xl, yl, n_order=n_order)\r\n\r\n return cst_u, cst_l\r\n\r\ndef scale_cst(x, yu, yl, cst_u, cst_l, t: float, tail=0.0):\r\n '''\r\n Scale CST coefficients, so that the airfoil has the maximum thickness of t. \r\n\r\n >>> cst_u_new, cst_l_new = scale_cst(yu, yl, cst_u, cst_l, t)\r\n\r\n ### Inputs:\r\n ```text\r\n x, yu, yl: baseline airfoil (ndarray)\r\n x, yu, yl must be directly generated by CST, without scaling\r\n cst_u, cst_l: CST coefficients (ndarray)\r\n t: target thickness\r\n tail: relative tail thickness (optional)\r\n ```\r\n '''\r\n\r\n thick = yu - yl\r\n it = np.argmax(thick)\r\n t0 = thick[it]\r\n\r\n r = (t-tail*x[it])/t0\r\n cst_u_new = cst_u * r\r\n cst_l_new = cst_l * r\r\n\r\n return cst_u_new, cst_l_new\r\n\r\ndef unify_foil(xu, yu, xl, yl):\r\n '''\r\n Transform the airfoil to a unit airfoil\r\n\r\n >>> xu_, yu_, xl_, yl_, twist, chord, tail = unify_foil(xu, yu, xl, yl)\r\n\r\n ### Return:\r\n ```text\r\n xu_, yu_, xl_, yl_: unit airfoil (ndarray)\r\n twist: twist angle (degree)\r\n chord: chord length\r\n tail: tail height relative to chord length\r\n ```\r\n '''\r\n if abs(xu[0]-xl[0])>1e-6 or abs(yu[0]-yl[0])>1e-6:\r\n raise Exception('Two curves do not have the same leading edge')\r\n \r\n #* Transform\r\n xu_ = xu - xu[0]\r\n xl_ = xl - xl[0]\r\n yu_ = yu - yu[0]\r\n yl_ = yl - yl[0]\r\n\r\n #* Twist\r\n xTE = 0.5*(xu_[-1]+xl_[-1])\r\n yTE = 0.5*(yu_[-1]+yl_[-1])\r\n twist = np.arctan(yTE/xTE)*180/np.pi\r\n chord = np.sqrt(xTE**2+yTE**2)\r\n\r\n xu_, yu_, _ = rotate(xu_, yu_, None, angle=-twist, axis='Z')\r\n xl_, yl_, _ = rotate(xl_, yl_, None, angle=-twist, axis='Z')\r\n\r\n #* Scale\r\n yu_ = yu_ / xu_[-1]\r\n yl_ = yl_ / xl_[-1]\r\n xu_ = xu_ / xu_[-1]\r\n xl_ = xl_ / xl_[-1]\r\n \r\n #* Removing tail\r\n tail = abs(yu_[-1]) + abs(yl_[-1])\r\n\r\n for ip in range(yu_.shape[0]):\r\n yu_[ip] -= xu_[ip]*yu_[-1] \r\n\r\n for ip in range(yl_.shape[0]):\r\n yl_[ip] -= xl_[ip]*yl_[-1] \r\n\r\n return xu_, yu_, xl_, yl_, twist, chord, tail\r\n\r\ndef fromCylinder(x, y, z, flip=True, origin=None):\r\n '''\r\n Bend the cylinder curve to a 2D plane curve.\r\n\r\n ### Inputs:\r\n ```text\r\n x, y ,z: ndarray, point coordinates of curves on the cylinder\r\n flip: if True, flip the X of plane curve\r\n origin: default None.\r\n if provided a list [x0, y0], then the cylinder origin is [x0, y0]\r\n ```\r\n\r\n ### Return:\r\n X, Y, Z: ndarray, point coordinates of curves bent to 2D X-Y planes\r\n\r\n ### Note:\r\n ```text\r\n Cylinder: origin (0,0,0), axis is z-axis\r\n x and y must not be 0 at the same time\r\n\r\n The origin of cylinder and plane curves is the same (0,0,0).\r\n \r\n Cylinder: x, y, z ~~ r, theta, z\r\n Plane: X, Y, Z\r\n\r\n theta = arctan(y/x)\r\n r = sqrt(x^2+y^2)\r\n z = z\r\n\r\n X = r*theta\r\n Y = z\r\n Z = r\r\n ```\r\n '''\r\n coef = -1.0 if flip else 1.0\r\n\r\n if origin is not None:\r\n x = x - origin[0]\r\n y = y - origin[1]\r\n\r\n rr = np.sqrt(x*x+y*y)\r\n tt = np.arctan2(y, x) * coef\r\n\r\n X = rr*tt\r\n Y = z.copy()\r\n Z = rr\r\n\r\n return X, Y, Z\r\n\r\ndef toCylinder(X, Y, Z, flip=True, origin=None):\r\n '''\r\n Bend the plane sections to curves on a cylinder.\r\n\r\n ### Inputs:\r\n ```text\r\n X, Y, Z: ndarray, point coordinates of curves on 2D X-Y planes\r\n Z must not be 0\r\n flip: if True, flip the X of plane curve\r\n origin: default None.\r\n if provided a list [x0, y0], then the cylinder origin is [x0, y0]\r\n ```\r\n\r\n ### Return:\r\n x, y ,z: ndarray, point coordinate of curves bent to a cylinder\r\n\r\n ### Note:\r\n ```text\r\n The origin of cylinder and plane curves is the same (0,0,0).\r\n \r\n Plane: X, Y, Z\r\n Cylinder: x, y, z ~~ r, theta, z\r\n \r\n theta = arctan(y/x)\r\n r = sqrt(x^2+y^2)\r\n z = z\r\n\r\n X = r*theta\r\n Y = z\r\n Z = r\r\n ```\r\n '''\r\n coef = -1.0 if flip else 1.0\r\n\r\n nn = X.shape[0]\r\n x = np.zeros(nn)\r\n y = np.zeros(nn)\r\n z = Y.copy()\r\n\r\n for i in range(nn):\r\n r = Z[i]\r\n theta = X[i]/r * coef\r\n x[i] = r*np.cos(theta)\r\n y[i] = r*np.sin(theta)\r\n\r\n if origin is not None:\r\n x = x + origin[0]\r\n y = y + origin[1]\r\n\r\n return x, y, z\r\n\r\n#* ===========================================\r\n#* Supportive functions\r\n#* ===========================================\r\n\r\ndef clustcos(i: int, nn: int, a0=0.0079, a1=0.96, beta=1.0) -> float:\r\n '''\r\n Point distribution on x-axis [0, 1]. (More points at both ends)\r\n\r\n >>> c = clustcos(i, n, a0, a1, beta)\r\n\r\n ### Inputs:\r\n ```text\r\n i: index of current point (start from 0)\r\n nn: total amount of points\r\n a0: parameter for distributing points near x=0\r\n a1: parameter for distributing points near x=1\r\n beta: parameter for distribution points \r\n ```\r\n '''\r\n aa = np.power((1-np.cos(a0*np.pi))/2.0, beta)\r\n dd = np.power((1-np.cos(a1*np.pi))/2.0, beta) - aa\r\n yt = i/(nn-1.0)\r\n a = np.pi*(a0*(1-yt)+a1*yt)\r\n c = (np.power((1-np.cos(a))/2.0,beta)-aa)/dd\r\n\r\n return c\r\n\r\ndef cst_curve(nn: int, coef: np.array, x=None, xn1=0.5, xn2=1.0):\r\n '''\r\n Generating single curve based on CST method.\r\n\r\n CST: class shape transfermation method (Kulfan, 2008)\r\n\r\n >>> x, y = cst_curve(nn, coef, x, xn1, xn2)\r\n\r\n ### Inputs:\r\n ```text\r\n nn: total amount of points\r\n coef: CST coefficients (ndarray)\r\n x: points x [0,1] (optional ndarray, size= nn)\r\n xn1,2: CST parameters\r\n ```\r\n ### Return:\r\n x, y (ndarray)\r\n '''\r\n if x is None:\r\n x = np.zeros(nn)\r\n for i in range(nn):\r\n x[i] = clustcos(i, nn)\r\n elif x.shape[0] != nn:\r\n raise Exception('Specified point distribution has different size %d as input nn %d'%(x.shape[0], nn))\r\n \r\n n_order = coef.shape[0]\r\n y = np.zeros(nn)\r\n for ip in range(nn):\r\n s_psi = 0.0\r\n for i in range(n_order):\r\n xk_i_n = factorial(n_order-1)/factorial(i)/factorial(n_order-1-i)\r\n s_psi += coef[i]*xk_i_n * np.power(x[ip],i) * np.power(1-x[ip],n_order-1-i)\r\n\r\n C_n1n2 = np.power(x[ip],xn1) * np.power(1-x[ip],xn2)\r\n y[ip] = C_n1n2*s_psi\r\n\r\n y[0] = 0.0\r\n y[-1] = 0.0\r\n\r\n return x, y\r\n\r\ndef find_circle_3p(p1, p2, p3):\r\n '''\r\n Determine the radius and origin of a circle by 3 points (2D)\r\n\r\n >>> R, XC = find_circle_3p(p1, p2, p3)\r\n\r\n ### Inputs:\r\n ```text\r\n p1, p2, p3: [x, y], list or ndarray\r\n ```\r\n\r\n ### Return: \r\n R, XC = np.array([xc, yc])\r\n '''\r\n\r\n # http://ambrsoft.com/TrigoCalc/Circle3D.htm\r\n\r\n A = p1[0]*(p2[1]-p3[1]) - p1[1]*(p2[0]-p3[0]) + p2[0]*p3[1] - p3[0]*p2[1]\r\n if np.abs(A) <= 1E-20:\r\n raise Exception('Finding circle: 3 points in one line')\r\n \r\n p1s = p1[0]**2 + p1[1]**2\r\n p2s = p2[0]**2 + p2[1]**2\r\n p3s = p3[0]**2 + p3[1]**2\r\n\r\n B = p1s*(p3[1]-p2[1]) + p2s*(p1[1]-p3[1]) + p3s*(p2[1]-p1[1])\r\n C = p1s*(p2[0]-p3[0]) + p2s*(p3[0]-p1[0]) + p3s*(p1[0]-p2[0])\r\n D = p1s*(p3[0]*p2[1]-p2[0]*p3[1]) + p2s*(p1[0]*p3[1]-p3[0]*p1[1]) + p3s*(p2[0]*p1[1]-p1[0]*p2[1])\r\n\r\n x0 = -B/2/A\r\n y0 = -C/2/A\r\n R = np.sqrt(B**2+C**2-4*A*D)/2/np.abs(A)\r\n\r\n '''\r\n x21 = p2[0] - p1[0]\r\n y21 = p2[1] - p1[1]\r\n x32 = p3[0] - p2[0]\r\n y32 = p3[1] - p2[1]\r\n\r\n if x21 * y32 - x32 * y21 == 0:\r\n raise Exception('Finding circle: 3 points in one line')\r\n\r\n xy21 = p2[0]*p2[0] - p1[0]*p1[0] + p2[1]*p2[1] - p1[1]*p1[1]\r\n xy32 = p3[0]*p3[0] - p2[0]*p2[0] + p3[1]*p3[1] - p2[1]*p2[1]\r\n \r\n y0 = (x32 * xy21 - x21 * xy32) / 2 * (y21 * x32 - y32 * x21)\r\n x0 = (xy21 - 2 * y0 * y21) / (2.0 * x21)\r\n R = np.sqrt(np.power(p1[0]-x0,2) + np.power(p1[1]-y0,2))\r\n '''\r\n\r\n return R, np.array([x0, y0])\r\n\r\ndef curve_curvature(x, y):\r\n '''\r\n Calculate curvature of points in the curve\r\n\r\n >>> curv = curve_curvature(x, y)\r\n\r\n ### Inputs:\r\n ```text\r\n x, y: points of curve (ndarray)\r\n ```\r\n\r\n Return: curv (ndarray)\r\n '''\r\n nn = x.shape[0]\r\n if nn<3:\r\n raise Exception('curvature needs at least 3 points')\r\n \r\n curv = np.zeros(nn)\r\n for i in range(1, nn-1):\r\n X1 = np.array([x[i-1], y[i-1]])\r\n X2 = np.array([x[i ], y[i ]])\r\n X3 = np.array([x[i+1], y[i+1]])\r\n\r\n a = np.linalg.norm(X1-X2)\r\n b = np.linalg.norm(X2-X3)\r\n c = np.linalg.norm(X3-X1)\r\n p = 0.5*(a+b+c)\r\n t = p*(p-a)*(p-b)*(p-c)\r\n R = a*b*c\r\n if R <= 1.0E-12:\r\n curv_ = 0.0\r\n else:\r\n curv_ = 4.0*np.sqrt(t)/R\r\n\r\n a1 = X2[0] - X1[0]\r\n a2 = X2[1] - X1[1]\r\n b1 = X3[0] - X1[0]\r\n b2 = X3[1] - X1[1]\r\n if a1*b2 < a2*b1:\r\n curv_ = -curv_\r\n\r\n curv[i] = curv_\r\n\r\n curv[0] = curv[1]\r\n curv[-1] = curv[-2]\r\n\r\n return curv\r\n\r\ndef transform(xu, xl, yu, yl, scale=1.0, rot=None, x0=None, y0=None, dx=0.0, dy=0.0, proj=False):\r\n '''\r\n Apply chord length, twist angle(deg) and leading edge position to unit airfoil\r\n\r\n >>> xu_new, xl_new, yu_new, yl_new = transform()\r\n\r\n ### Inputs:\r\n ```text\r\n xu, xl, yu, yl: current curve or unit airfoil (ndarray)\r\n scale: scale factor, e.g., chord length\r\n rot: rotate angle (deg), +z direction for x-y plane, \r\n e.g., twist angle\r\n x0, y0: rotation and scale center\r\n dx, dy: translation, e.g., leading edge location\r\n proj: if True, for unit airfoil, the rotation keeps \r\n the projection length the same\r\n ```\r\n\r\n ### Return: \r\n ```text\r\n xu_new, xl_new, yu_new, yl_new (ndarray)\r\n ```\r\n '''\r\n #* Translation\r\n xu_new = dx + xu\r\n xl_new = dx + xl\r\n yu_new = dy + yu\r\n yl_new = dy + yl\r\n\r\n #* Rotation center\r\n if x0 is None:\r\n x0 = xu_new[0]\r\n if y0 is None:\r\n y0 = 0.5*(yu_new[0]+yl_new[0])\r\n \r\n #* Scale (keeps the same projection length)\r\n rr = 1.0\r\n if proj and not rot is None:\r\n angle = rot/180.0*np.pi # rad\r\n rr = np.cos(angle)\r\n\r\n xu_new = x0 + (xu_new-x0)*scale/rr\r\n xl_new = x0 + (xl_new-x0)*scale/rr\r\n yu_new = y0 + (yu_new-y0)*scale/rr\r\n yl_new = y0 + (yl_new-y0)*scale/rr\r\n\r\n #* Rotation\r\n if not rot is None:\r\n xu_new, yu_new, _ = rotate(xu_new, yu_new, None, angle=rot, origin=[x0, y0, 0.0], axis='Z')\r\n xl_new, yl_new, _ = rotate(xl_new, yl_new, None, angle=rot, origin=[x0, y0, 0.0], axis='Z')\r\n\r\n return xu_new, xl_new, yu_new, yl_new\r\n\r\ndef rotate(x, y, z, angle=0.0, origin=[0.0, 0.0, 0.0], axis='X'):\r\n '''\r\n Rotate the 3D curve according to origin\r\n\r\n >>> x_, y_, z_ = rotate(x, y, z, angle, origin, axis)\r\n\r\n ### Inputs:\r\n ```text\r\n x,y,z: curve ndarray\r\n angle: rotation angle (deg)\r\n origin: rotation origin\r\n axis: rotation axis (use positive direction to define angle)\r\n ```\r\n\r\n ### Return:\r\n x_, y_, z_ (ndarray)\r\n '''\r\n cc = np.cos( angle/180.0*np.pi )\r\n ss = np.sin( angle/180.0*np.pi )\r\n x_ = copy.deepcopy(x)\r\n y_ = copy.deepcopy(y)\r\n z_ = copy.deepcopy(z)\r\n\r\n if axis in 'X':\r\n y_ = origin[1] + (y-origin[1])*cc - (z-origin[2])*ss\r\n z_ = origin[2] + (y-origin[1])*ss + (z-origin[2])*cc\r\n\r\n if axis in 'Y':\r\n z_ = origin[2] + (z-origin[2])*cc - (x-origin[0])*ss\r\n x_ = origin[0] + (z-origin[2])*ss + (x-origin[0])*cc\r\n\r\n if axis in 'Z':\r\n x_ = origin[0] + (x-origin[0])*cc - (y-origin[1])*ss\r\n y_ = origin[1] + (x-origin[0])*ss + (y-origin[1])*cc\r\n\r\n return x_, y_, z_\r\n\r\ndef interplot_from_curve(x0, x, y) -> np.ndarray:\r\n '''\r\n Interplot points from curve represented points [x, y]\r\n\r\n >>> y0 = interplot_from_curve(x0, x, y)\r\n\r\n ### Inputs:\r\n ```text\r\n x0 : ndarray/value of x locations to be interploted\r\n x, y: points of curve (ndarray)\r\n ```\r\n\r\n ### Return: \r\n y0: ndarray/float\r\n '''\r\n f = interp1d(x, y, kind='cubic')\r\n y0 = f(x0)\r\n\r\n return y0\r\n\r\ndef curve_intersect(x1, y1, x2, y2):\r\n '''\r\n Find the intersect index between two curves.\r\n\r\n >>> i1, i2, points = curve_intersect(x1, y1, x2, y2)\r\n\r\n ### Inputs:\r\n ```text\r\n x1, y1: curve 1 coordinates, list or ndarray\r\n x2, y2: curve 2 coordinates, list or ndarray\r\n ```\r\n\r\n ### Return:\r\n ```text\r\n i1, i2: index of the closest points in curve 1 & 2\r\n points: tuple of two closest points in curve 1 & 2\r\n ```\r\n '''\r\n\r\n arr1 = np.vstack((np.array(x1),np.array(y1))).T\r\n arr2 = np.vstack((np.array(x2),np.array(y2))).T\r\n\r\n tree = spatial.KDTree(arr2)\r\n distance, arr2_index = tree.query(arr1)\r\n i1 = distance.argmin() # type: int\r\n i2 = arr2_index[i1] # type: int\r\n points = (arr1[i1], arr2[i2])\r\n\r\n return i1, i2, points\r\n\r\ndef stretch_fixed_point(x, y, dx=0.0, dy=0.0, xm=None, ym=None, xf=None, yf=None):\r\n '''\r\n Linearly stretch a curve when certain point is fixed\r\n\r\n >>> x_, y_ = stretch_fixed_point(x, y, dx, dy, xm, ym, xf, yf)\r\n\r\n ### Inputs:\r\n ```text\r\n x, y: curve (ndarray)\r\n dx, dy: movement of the first element (scaler)\r\n xm, ym: The point that moves dx, dy (e.g., the first element of the curve)\r\n xf, yf: The fixed point (e.g., the last element of the curve)\r\n ```\r\n\r\n ### Returns:\r\n x_, y_ (ndarray)\r\n '''\r\n x_ = x.copy()\r\n y_ = y.copy()\r\n\r\n if xf is None or yf is None:\r\n xf = x[-1]\r\n yf = y[-1]\r\n\r\n if xm is None or ym is None:\r\n xm = x[0]\r\n ym = y[0]\r\n\r\n lm = np.linalg.norm([xm-xf, ym-yf])\r\n\r\n for i in range(x.shape[0]):\r\n rr = np.linalg.norm([x[i]-xf, y[i]-yf]) / lm\r\n x_[i] = x_[i] + rr*dx\r\n y_[i] = y_[i] + rr*dy\r\n\r\n return x_, y_\r\n\r\ndef add_bump(x, y, xc: float, h: float, s: float, kind='G'):\r\n '''\r\n Add a bump on current curve [x, y]\r\n\r\n >>> y_new = add_bump(x, y, xc, h, s, kind)\r\n\r\n ### Inputs:\r\n ```text\r\n x, y: current curve (ndarray, x[0,1])\r\n xc: x of the bump center\r\n h: height of the bump\r\n s: span of the bump\r\n kind: bump function\r\n 'G': Gaussian, less cpu cost\r\n 'H': Hicks-Henne, better when near leading edge\r\n ```\r\n\r\n ### Return: \r\n y_new (ndarray, new curve)\r\n '''\r\n y_new = y.copy()\r\n\r\n if xc<=0 or xc>=1:\r\n print('Bump location not valid (0,1): xc = %.3f'%(xc))\r\n return y_new\r\n\r\n if 'G' in kind:\r\n\r\n for i in range(x.shape[0]):\r\n if xc-s<0.0 and x[i]<xc:\r\n sigma = xc/3.5\r\n elif xc+s>1.0 and x[i]>xc:\r\n sigma = (1.0-xc)/3.5\r\n else:\r\n sigma = s/6.0\r\n aa = -np.power(x[i]-xc,2)/2.0/sigma**2\r\n y_new[i] += h*np.exp(aa)\r\n\r\n else:\r\n \r\n s0 = np.log(0.5)/np.log(xc) \r\n\r\n Pow = 1\r\n span = 1.0\r\n hm = np.abs(h)\r\n while Pow<100 and span>s:\r\n x1 = -1.0\r\n x2 = -1.0\r\n for i in range(0, 201):\r\n xx = i*0.005\r\n rr = np.pi*np.power(xx,s0)\r\n yy = hm * np.power(np.sin(rr),Pow)\r\n if yy > 0.01*hm and x1<0.0 and xx<xc:\r\n x1 = xx\r\n if yy < 0.01*hm and x2<0.0 and xx>xc:\r\n x2 = xx\r\n if x2 < 0.0:\r\n x2 = 1.0\r\n \r\n span = x2 - x1\r\n Pow = Pow + 1\r\n\r\n for i in range(len(x)):\r\n rr = np.pi*np.power(x[i],s0)\r\n dy = h*np.power(np.sin(rr),Pow)\r\n y_new[i] += dy\r\n\r\n return y_new\r\n\r\ndef fit_curve(x: np.array, y: np.array, n_cst=7, xn1=0.5, xn2=1.0):\r\n '''\r\n Using least square method to fit a CST curve\r\n\r\n >>> coef = fit_curve(x, y, n_cst, xn1, xn2)\r\n\r\n ### Input:\r\n ```text\r\n x, y: curve points (ndarray)\r\n n_cst: number of CST parameters\r\n ```\r\n\r\n ### Attributes:\r\n ```text\r\n Array A: A[nn, n_order], nn=len(x)\r\n Array b: b[nn]\r\n ```\r\n\r\n ### Return: \r\n coef (ndarray)\r\n '''\r\n nn = x.shape[0]\r\n L = x[-1] - x[0] # type: float\r\n x_ = (x-x[0])/L # scaling x to 0~1\r\n y_ = (y-y[0])/L # scaling according to L\r\n b = y_.copy()\r\n\r\n for ip in range(nn):\r\n b[ip] -= x_[ip]*y_[-1] # removing tail\r\n\r\n A = np.zeros((nn, n_cst))\r\n for ip in range(nn):\r\n C_n1n2 = np.power(x_[ip],xn1) * np.power(1-x_[ip],xn2)\r\n for i in range(n_cst):\r\n xk_i_n = factorial(n_cst-1)/factorial(i)/factorial(n_cst-1-i)\r\n A[ip][i] = xk_i_n * np.power(x_[ip],i) * np.power(1-x_[ip],n_cst-1-i) * C_n1n2\r\n\r\n solution = lstsq(A, b, rcond=None)\r\n\r\n return solution[0]\r\n\r\ndef fit_curve_with_twist(x, y, n_cst=7, xn1=0.5, xn2=1.0):\r\n '''\r\n Using least square method to fit a CST curve\r\n\r\n >>> coef, chord, twist, thick = fit_curve_with_twist(x, y, n_cst, xn1, xn2)\r\n\r\n ### Input:\r\n ```text\r\n x, y: curve points (ndarray)\r\n n_cst: number of CST parameters\r\n ```\r\n\r\n ### Attributes:\r\n ```text\r\n Array A: A[nn, n_order], nn=len(x)\r\n Array b: b[nn]\r\n ```\r\n\r\n ### Return: \r\n coef: CST parameters, ndarray\r\n chord: distance between two ends of the curve\r\n twist: degree, +z axis\r\n thick: maximum relative thickness\r\n '''\r\n chord = np.sqrt((x[0]-x[-1])**2+(y[0]-y[-1])**2)\r\n twist = np.arctan((y[-1]-y[0])/(x[-1]-x[0]))*180/np.pi\r\n\r\n x_ = (x - x[0])/chord\r\n y_ = (y - y[0])/chord\r\n x_, y_, _ = rotate(x_, y_, None, angle=-twist, axis='Z')\r\n thick = np.max(y_, axis=0)\r\n\r\n coef = fit_curve(x_, y_, n_cst=n_cst, xn1=xn1, xn2=xn2)\r\n \r\n return coef, chord, twist, thick\r\n\r\ndef fit_curve_partial(x: np.array, y: np.array, ip0=0, ip1=0,\r\n n_cst=7, ic0=0, ic1=0, xn1=0.5, xn2=1.0):\r\n '''\r\n Using least square method to fit a part of a unit curve\r\n\r\n >>> coef = fit_curve_partial(x: np.array, y: np.array,\r\n >>> ip0=0, ip1=0, n_cst=7, xn1=0.5, xn2=1.0)\r\n\r\n ### Input:\r\n ```text\r\n x, y: curve points (ndarray)\r\n ip0, ip1: index of the partial curve x[ip0:ip1] \r\n ic0, ic1: index of the CST parameters cst[ic0:ic1] that are not 0\r\n n_cst: number of CST parameters\r\n ```\r\n\r\n ### Attributes:\r\n ```text\r\n Array A: A[nn, n_order], nn=len(x)\r\n Array b: b[nn]\r\n ```\r\n\r\n ### Return: \r\n coef (ndarray)\r\n '''\r\n ip0 = max(0, ip0)\r\n if ip1 <= ip0:\r\n ip1 = x.shape[0]\r\n\r\n ic0 = max(0, ic0)\r\n if ic1 <= ic0:\r\n ic1 = n_cst\r\n\r\n #* Fit the partial curve\r\n A = np.zeros((ip1-ip0, ic1-ic0))\r\n for ip in range(ip0, ip1):\r\n C_n1n2 = np.power(x[ip],xn1) * np.power(1-x[ip],xn2)\r\n for i in range(ic0,ic1):\r\n xk_i_n = factorial(n_cst-1)/factorial(i)/factorial(n_cst-1-i)\r\n A[ip-ip0][i-ic0] = xk_i_n * np.power(x[ip],i) * np.power(1-x[ip],n_cst-1-i) * C_n1n2\r\n\r\n solution = lstsq(A, y[ip0:ip1], rcond=None)\r\n\r\n return solution[0]\r\n\r\ndef output_foil(x, yu, yl, fname='airfoil.dat', ID=0, info=False):\r\n '''\r\n Output airfoil data to tecplot ASCII format file\r\n\r\n ### Inputs:\r\n ```text\r\n x, yu, yl: current airfoil (ndarray)\r\n ID: >0 append to existed file. 0: write header\r\n info: True: include curvature, thickness and camber\r\n ```\r\n '''\r\n nn = x.shape[0]\r\n curv_u = np.zeros(nn)\r\n curv_l = np.zeros(nn)\r\n camber = np.zeros(nn)\r\n thickness = np.zeros(nn)\r\n \r\n if ID == 0:\r\n # Write header\r\n with open(fname, 'w') as f:\r\n if info: \r\n line = 'Variables= X Y Curvature Thickness Camber \\n '\r\n else:\r\n line = 'Variables= X Y \\n '\r\n f.write(line)\r\n\r\n if info:\r\n thickness, curv_u, curv_l, camber = foil_tcc(x, yu, yl, info=info)\r\n\r\n with open(fname, 'a') as f:\r\n f.write('zone T=\"Upp-%d\" i= %d \\n'%(ID, nn))\r\n for i in range(nn):\r\n line = ' %20.9f %20.9f'%(x[i], yu[i])\r\n if info:\r\n line = line + ' %20.9f %20.9f %20.9f'%(curv_u[i], thickness[i], camber[i])\r\n f.write(line+'\\n')\r\n \r\n f.write('zone T=\"Low-%d\" i= %d \\n'%(ID, nn))\r\n for i in range(nn):\r\n line = ' %20.9f %20.9f'%(x[i], yl[i])\r\n if info:\r\n line = line + ' %20.9f %20.9f %20.9f'%(curv_l[i], thickness[i], camber[i])\r\n f.write(line+'\\n')\r\n\r\ndef output_curve(x, y, fname='curve.dat', ID=0):\r\n '''\r\n Output airfoil data to tecplot ASCII format file\r\n\r\n ### Inputs:\r\n ```text\r\n x, y: current curve (ndarray)\r\n ID: >0 append to existed file. 0: write header\r\n ```\r\n '''\r\n nn = x.shape[0]\r\n\r\n if ID == 0:\r\n with open(fname, 'w') as f:\r\n f.write('Variables= X Y \\n ')\r\n\r\n with open(fname, 'a') as f:\r\n f.write('zone T=\"%d\" i= %d \\n'%(ID, nn))\r\n for i in range(nn):\r\n f.write(' %20.9f %20.9f \\n'%(x[i], y[i]))\r\n f.write('\\n')\r\n\r\ndef read_curves(fname='curve.dat'):\r\n '''\r\n Read curves from a tecplot format file.\r\n\r\n >>> xs, ys = read_curves(fname='curve.dat')\r\n\r\n ### Return:\r\n ```text\r\n xs, ys: list [list]\r\n len(xs) = len(ys) = number of curves\r\n len(xs[i]) = number of points on curve i\r\n ```\r\n '''\r\n\r\n xs = []\r\n ys = []\r\n with open('original.dat', 'r') as f:\r\n lines = f.readlines()\r\n\r\n for line in lines:\r\n\r\n line = line.split()\r\n if len(line)<=1:\r\n continue\r\n\r\n if line[0] in 'zone':\r\n xs.append([])\r\n ys.append([])\r\n continue\r\n\r\n if len(line)!=2:\r\n continue \r\n \r\n xs[-1].append(float(line[0]))\r\n ys[-1].append(float(line[1]))\r\n\r\n return xs, ys\r\n\r\n#* ===========================================\r\n#* For compressor/turbine blades\r\n#* ===========================================\r\n\r\ndef cst_foil_roundtail(nn, cst_u, cst_l, cst_tu, cst_tl, n_rev=10, x=None, t=None):\r\n '''\r\n Constructing upper and lower curves of an airfoil based on CST method\r\n\r\n CST: class shape transfermation method (Kulfan, 2008)\r\n\r\n >>> x_, yu, yl, t0, R0, (yu_rev, yl_rev) = \r\n >>> cst_foil_roundtail(nn, cst_u, cst_l, \r\n >>> cst_tu, cst_tl, n_rev=10, x=None, t=None)\r\n\r\n ### Inputs:\r\n ```text\r\n nn: total amount of points\r\n cst_u, cst_l: CST coefficients of upper/lower surface (ndarray)\r\n cst_tu, cst_tl: the (1st) coefficient of the CST curve describing the round tail\r\n n_rev: order of CST for round tail\r\n x: point x [0,1] (optional ndarray, size is nn)\r\n t: relative maximum thickness (optional)\r\n ```\r\n\r\n ### Return\r\n ```text\r\n x (ndarray), y_upp (ndarray), y_low (ndarray), t0, R0\r\n ```\r\n '''\r\n x_, yu_ = cst_curve(nn, cst_u, x=x)\r\n x_, yl_ = cst_curve(nn, cst_l, x=x)\r\n\r\n rev_u = np.zeros(n_rev)\r\n rev_l = np.zeros(n_rev)\r\n if isinstance(cst_tu, float):\r\n rev_u[0] = cst_tu\r\n elif isinstance(cst_tu, np.ndarray):\r\n rev_u[:cst_tu.shape[0]] = cst_tu\r\n else:\r\n raise Exception('Wrong type of cst_tu')\r\n\r\n if isinstance(cst_tl, float):\r\n rev_l[0] = cst_tl\r\n elif isinstance(cst_tl, np.ndarray):\r\n rev_l[:cst_tl.shape[0]] = cst_tl\r\n else:\r\n raise Exception('Wrong type of cst_tl')\r\n\r\n _, yu_rev = cst_curve(nn, rev_u, x=1.0-x_)\r\n _, yl_rev = cst_curve(nn, rev_l, x=1.0-x_)\r\n\r\n yu = yu_ + yu_rev\r\n yl = yl_ + yl_rev\r\n\r\n thick = yu-yl\r\n t0 = np.max(thick)\r\n\r\n #* Apply thickness constraint\r\n if t is not None:\r\n r = t/t0\r\n t0 = t\r\n yu = yu * r\r\n yl = yl * r\r\n\r\n # Calculate leading edge radius\r\n x_RLE = 0.005\r\n yu_RLE = interplot_from_curve(x_RLE, x_, yu)\r\n yl_RLE = interplot_from_curve(x_RLE, x_, yl)\r\n R0, _ = find_circle_3p([0.0,0.0], [x_RLE,yu_RLE], [x_RLE,yl_RLE])\r\n\r\n return x_, yu, yl, t0, R0, (yu_rev, yl_rev)\r\n\r\ndef fit_curve_roundtail(x, y, n_cst=7, n_rev=10, n_tail=1, ratio_tail=0.1, xn1=0.5, xn2=1.0):\r\n '''\r\n Using CST method to fit a curve with a round tail\r\n\r\n This function allows the curve chord length not equals to one.\r\n Also allows the curve has a twist angle.\r\n\r\n >>> cst, coef_tail = fit_curve_roundtail(x, y, \r\n >>> n_cst=7, n_rev=10, n_tail=1, ratio_tail=0.1, xn1=0.5, xn2=1.0)\r\n\r\n ### Inputs:\r\n ```text\r\n x, y: curve points, ndarray\r\n n_cst: number of CST parameters\r\n n_rev: size of cst_rev (ndarray), which is the CST parameters for \r\n the reverse curve (y_tail) that is used to describe the round tail\r\n n_tail: the first n_tail CST coefficients in cst_rev are not zero \r\n ratio_tail: the reverse curve (y_tail) is used to mainly describe (1-ratio_tail~1)\r\n part of the entire curve\r\n ```\r\n\r\n ### Return: \r\n ```text\r\n cst_u, cst_l: ndarray [n_cst], the CST coefficients describing the remaining curve,\r\n i.e., the original y substracts the round tail curve (y_tail)\r\n coef_tail: ndarray [n_tail], the first n_tail CST coefficients\r\n for the reverse curve (y_tail) that is used to describe the round tail\r\n ```\r\n '''\r\n n0 = x.shape[0]\r\n n_tail = max(1, min(n_tail, n_rev))\r\n\r\n #* Curve with twist and chord not 1.0\r\n chord = np.sqrt((x[0]-x[-1])**2+(y[0]-y[-1])**2)\r\n twist = np.arctan((y[-1]-y[0])/(x[-1]-x[0]))*180/np.pi\r\n\r\n x_ = (x - x[0])/chord\r\n y_ = (y - y[0])/chord\r\n x_, y_, _ = rotate(x_, y_, None, angle=-twist, axis='Z')\r\n\r\n #* Fit the trailing part\r\n ip1 = max(2, int(ratio_tail*n0))\r\n coef_tail = fit_curve_partial(x_, np.flip(y_), ip0=0, ip1=ip1,\r\n n_cst=n_rev, ic0=0, ic1=n_tail, xn1=xn1, xn2=xn2)\r\n\r\n cst_rev = np.zeros(n_rev)\r\n cst_rev[:n_tail] = coef_tail\r\n _, y_tail = cst_curve(n0, cst_rev, x=1.0-x_, xn1=xn1, xn2=xn2)\r\n \r\n #* Fit the remaining curve\r\n coef = fit_curve(x_, y_-y_tail, n_cst=n_cst, xn1=xn1, xn2=xn2)\r\n\r\n return coef, coef_tail\r\n\r\ndef cst_foil_roundend(nn, cst_u, cst_l, cst_lu, cst_ll, n_lead_all,\r\n cst_tu, cst_tl, n_tail_all, x=None, t=None):\r\n '''\r\n Constructing upper and lower curves of an airfoil based on CST method\r\n\r\n CST: class shape transfermation method (Kulfan, 2008)\r\n\r\n >>> x_, yu, yl, t0, R0, (yu_lead, yl_lead), (yu_tail, yl_tail) = \r\n >>> cst_foil_roundend(nn, cst_u, cst_l, cst_lu, cst_ll, n_lead_all,\r\n >>> cst_tu, cst_tl, n_tail_all, x=None, t=None)\r\n\r\n ### Inputs:\r\n ```text\r\n nn: total amount of points\r\n cst_u, cst_l: CST coefficients of upper/lower surface (ndarray)\r\n cst_lu, cst_ll: the (1st) coefficient of the CST curve describing the round leading edge\r\n cst_tu, cst_tl: the (1st) coefficient of the CST curve describing the round tail\r\n n_lead_all: order of CST for round leading edge\r\n n_tail_all: order of CST for round tail\r\n x: point x [0,1] (optional ndarray, size is nn)\r\n t: relative maximum thickness (optional)\r\n ```\r\n\r\n ### Return\r\n x (ndarray), y_upp (ndarray), y_low (ndarray), t0, R0\r\n '''\r\n #* Baseline curve\r\n x_, yu_ = cst_curve(nn, cst_u, x=x)\r\n x_, yl_ = cst_curve(nn, cst_l, x=x)\r\n\r\n #* Round leading edge\r\n lead_u = np.zeros(n_lead_all)\r\n lead_l = np.zeros(n_lead_all)\r\n if isinstance(cst_lu, float):\r\n lead_u[0] = cst_lu\r\n elif isinstance(cst_lu, np.ndarray):\r\n lead_u[:cst_lu.shape[0]] = cst_lu\r\n else:\r\n raise Exception('Wrong type of cst_lu')\r\n\r\n if isinstance(cst_ll, float):\r\n lead_l[0] = cst_ll\r\n elif isinstance(cst_ll, np.ndarray):\r\n lead_l[:cst_ll.shape[0]] = cst_ll\r\n else:\r\n raise Exception('Wrong type of cst_ll')\r\n\r\n _, yu_lead = cst_curve(nn, lead_u, x=x_)\r\n _, yl_lead = cst_curve(nn, lead_l, x=x_)\r\n\r\n #* Round tail\r\n rev_u = np.zeros(n_tail_all)\r\n rev_l = np.zeros(n_tail_all)\r\n if isinstance(cst_tu, float):\r\n rev_u[0] = cst_tu\r\n elif isinstance(cst_tu, np.ndarray):\r\n rev_u[:cst_tu.shape[0]] = cst_tu\r\n else:\r\n raise Exception('Wrong type of cst_tu')\r\n\r\n if isinstance(cst_tl, float):\r\n rev_l[0] = cst_tl\r\n elif isinstance(cst_tl, np.ndarray):\r\n rev_l[:cst_tl.shape[0]] = cst_tl\r\n else:\r\n raise Exception('Wrong type of cst_tl')\r\n\r\n _, yu_tail = cst_curve(nn, rev_u, x=1.0-x_)\r\n _, yl_tail = cst_curve(nn, rev_l, x=1.0-x_)\r\n\r\n #* Combine\r\n yu = yu_ + yu_lead + yu_tail\r\n yl = yl_ + yl_lead + yl_tail\r\n\r\n thick = yu-yl\r\n t0 = np.max(thick)\r\n\r\n #* Apply thickness constraint\r\n if t is not None:\r\n r = t/t0\r\n t0 = t\r\n yu = yu * r\r\n yl = yl * r\r\n\r\n # Calculate leading edge radius\r\n x_RLE = 0.005\r\n yu_RLE = interplot_from_curve(x_RLE, x_, yu)\r\n yl_RLE = interplot_from_curve(x_RLE, x_, yl)\r\n R0, _ = find_circle_3p([0.0,0.0], [x_RLE,yu_RLE], [x_RLE,yl_RLE])\r\n\r\n return x_, yu, yl, t0, R0, (yu_lead, yl_lead), (yu_tail, yl_tail)\r\n\r\ndef fit_curve_roundend(x, y, n_cst=7, n_lead_all=10, n_lead=1, ratio_lead=0.1, \r\n n_tail_all=10, n_tail=1, ratio_tail=0.1, xn1=0.5, xn2=1.0):\r\n '''\r\n Using CST method to fit a curve with round ends\r\n\r\n This function allows the curve chord length not equals to one.\r\n Also allows the curve has a twist angle.\r\n\r\n >>> cst_u, cst_l, coef_tail = fit_curve_roundtail(x, y, \r\n >>> n_cst=7, n_rev=10, n_tail=1, ratio_tail=0.1, xn1=0.5, xn2=1.0)\r\n\r\n ### Inputs:\r\n ```text\r\n x, y: curve points, ndarray\r\n n_cst: number of CST parameters\r\n n_tail_all: size of cst_rev (ndarray), which is the CST parameters for \r\n the reverse curve (y_tail) that is used to describe the round tail\r\n n_tail: the first n_tail CST coefficients in cst_rev are not zero \r\n ratio_tail: the reverse curve (y_tail) is used to mainly describe (1-ratio_tail~1)\r\n part of the entire curve\r\n ```\r\n\r\n ### Return: \r\n ```text\r\n cst_u, cst_l: ndarray [n_cst], the CST coefficients describing the remaining curve,\r\n i.e., the original y substracts the round tail curve (y_tail)\r\n coef_tail: ndarray [n_tail], the first n_tail CST coefficients\r\n for the reverse curve (y_tail) that is used to describe the round tail\r\n ```\r\n '''\r\n n0 = x.shape[0]\r\n n_lead = max(1, min(n_lead, n_lead_all))\r\n n_tail = max(1, min(n_tail, n_tail_all))\r\n\r\n #* Curve with twist and chord not 1.0\r\n chord = np.sqrt((x[0]-x[-1])**2+(y[0]-y[-1])**2)\r\n twist = np.arctan((y[-1]-y[0])/(x[-1]-x[0]))*180/np.pi\r\n\r\n x_ = (x - x[0])/chord\r\n y_ = (y - y[0])/chord\r\n x_, y_, _ = rotate(x_, y_, None, angle=-twist, axis='Z')\r\n\r\n #* Fit the leading part\r\n ip1 = max(2, int(ratio_lead*n0))\r\n coef_lead = fit_curve_partial(x_, y_, ip0=0, ip1=ip1,\r\n n_cst=n_lead_all, ic0=0, ic1=n_lead, xn1=xn1, xn2=xn2)\r\n\r\n cst_lead = np.zeros(n_lead_all)\r\n cst_lead[:n_lead] = coef_lead\r\n _, y_lead = cst_curve(n0, cst_lead, x=x_, xn1=xn1, xn2=xn2)\r\n\r\n #* Fit the trailing part\r\n ip1 = max(2, int(ratio_tail*n0))\r\n coef_tail = fit_curve_partial(x_, np.flip(y_), ip0=0, ip1=ip1,\r\n n_cst=n_tail_all, ic0=0, ic1=n_tail, xn1=xn1, xn2=xn2)\r\n\r\n cst_rev = np.zeros(n_tail_all)\r\n cst_rev[:n_tail] = coef_tail\r\n _, y_tail = cst_curve(n0, cst_rev, x=1.0-x_, xn1=xn1, xn2=xn2)\r\n \r\n #* Fit the remaining curve\r\n coef = fit_curve(x_, y_-y_lead-y_tail, n_cst=n_cst, xn1=xn1, xn2=xn2)\r\n\r\n return coef, coef_lead, coef_tail\r\n\r\n\r\n\r\n\r\n\r\n"
] | [
[
"scipy.special.factorial",
"scipy.interpolate.interp1d",
"scipy.spatial.KDTree",
"numpy.ones_like",
"numpy.log",
"numpy.abs",
"numpy.cos",
"numpy.zeros",
"numpy.argmax",
"numpy.max",
"numpy.power",
"numpy.min",
"numpy.array",
"numpy.linalg.norm",
"numpy.arctan2",
"numpy.arctan",
"numpy.exp",
"numpy.linalg.lstsq",
"numpy.flip",
"numpy.sqrt",
"numpy.sin"
]
] |
breno-aberle/rl-pong-project | [
"9dc0d12e4bbcdb2905d46f66e84fac6d70c7831d"
] | [
"training_ac.py"
] | [
"import torch\nimport gym\nimport numpy as np\nimport argparse\nimport cv2\nimport matplotlib.pyplot as plt\nfrom agent_ac import Agent, Policy\nfrom wimblepong import Wimblepong # import wimblepong-environment\nimport pandas as pd\nfrom PIL import Image\nfrom collections import deque\nimport os\nfrom torch.utils.tensorboard import SummaryWriter\n\n\n\n# Policy training function\ndef train(env_name, print_things=True, train_run_id=0, train_episodes=5000):\n # Create a Gym environment\n env = gym.make(env_name)\n best=0\n exp_name = 'ACTOR CRITIC SCRATCH'\n experiment_name = exp_name\n data_path = os.path.join('data', experiment_name)\n models_path = f\"{data_path}/models\"\n import wandb\n wandb.init(project=args.wandb_project_name, entity=args.wandb_entity, sync_tensorboard=True, config=vars(args), name=exp_name, monitor_gym=True, save_code=True)\n writer = SummaryWriter(f\"/tmp/{exp_name}\")\n\n # Get dimensionalities of actions and observations\n action_space_dim = env.action_space.shape\n observation_space_dim = env.observation_space.shape\n # Instantiate agent and its policy\n policy = Policy(observation_space_dim, action_space_dim)\n agent = Agent(policy)\n agent.load_model()\n\n # Arrays to keep track of rewards\n reward_history, timestep_history = [], []\n average_reward_history = []\n counter = 0\n\n # Run actual training\n for episode_number in range(train_episodes):\n reward_sum, timesteps = 0, 0\n done = False\n # Reset the environment and observe the initial state\n observation = env.reset()\n observation = np.array(observation)\n\n # Loop until the episode is over\n while not done:\n # Get action from the agent, an action gets chosen based on the img_stacked processed.\n action, action_probabilities = agent.get_action(observation)\n previous_observation = observation\n\n # Perform the action on the environment, get new state and reward. Now we perform a new step, to see what happens with the action in our current state, the result is the next state\n observation, reward, done, info = env.step(action.detach().cpu().numpy())\n\n #env.render()\n # Store action's outcome (so that the agent can improve its policy)\n agent.store_outcome(previous_observation, observation, action_probabilities, reward, done)\n\n # Store total episode reward\n reward_sum += reward\n timesteps += 1\n counter += 1\n \"\"\" if counter%160==0 and episode_number<100001:\n agent.update_policy(episode_number, episode_done=done)\n if counter%320==0 and episode_number<600950 and episode_number>100000:\n agent.update_policy(episode_number, episode_done=done)\n if counter%450==0 and episode_number>600949:\n agent.update_policy(episode_number, episode_done=done) \"\"\"\n\n # Update the actor-critic code to perform TD(0) updates every 50 timesteps\n #if timesteps%45==0 and not done:\n # agent.update_policy(episode_number, episode_done=done)\n\n if print_things:\n print(\"Episode {} finished. Total reward: {:.3g} ({} timesteps)\"\n .format(episode_number, reward_sum, timesteps))\n writer.add_scalar('Training ' + env_name, reward_sum, episode_number)\n writer.add_scalar('Training Timesteps ' + env_name, timesteps, episode_number)\n if episode_number%60==0 and episode_number!=0:\n agent.update_policy(episode_number, episode_done=done)\n # Bookkeeping (mainly for generating plots)\n reward_history.append(reward_sum)\n timestep_history.append(timesteps)\n if episode_number > 100:\n avg = np.mean(reward_history[-100:])\n else:\n avg = np.mean(reward_history)\n average_reward_history.append(avg)\n\n # Let the agent do its magic (update the policy)\n #COMMENT FOR TASK 2-3 NEXT LINE - UNCOMMENT TASK 1\n #agent.update_policy(episode_number, episode_done=done)\n if avg>best and episode_number >1000:\n best=avg\n torch.save(agent.policy_net.state_dict(),\"ACBEST.mdl\")\n # save model:\n if episode_number % 6503 == 0 and episode_number != 0:\n torch.save(agent.policy.state_dict(), \"ACCOOL2%s_%d.mdl\" % (env_name, episode_number))\n\n # Training is finished - plot rewards\n if print_things:\n plt.plot(timestep_history)\n plt.legend([\"Reward\", \"100-episode average\"])\n plt.title(\"AC reward history (non-episodic)\")\n plt.show()\n plt.plot(reward_history)\n plt.plot(average_reward_history)\n plt.legend([\"Reward\", \"100-episode average\"])\n plt.title(\"AC reward history (non-episodic)\")\n plt.show()\n print(\"Training finished.\")\n data = pd.DataFrame({\"episode\": np.arange(len(reward_history)),\n \"train_run_id\": [train_run_id]*len(reward_history),\n # TODO: Change algorithm name for plots, if you want\n \"algorithm\": [\"Non-Episodic AC\"]*len(reward_history),\n \"reward\": reward_history})\n torch.save(agent.policy.state_dict(), \"ACSCRATCH%s_%d.mdl\" % (env_name, train_run_id))\n return data\n\n\n# Function to test a trained policy\ndef test(env_name, episodes, params, render):\n # Create a Gym environment\n env = gym.make(env_name)\n\n # Get dimensionalities of actions and observations\n action_space_dim = env.action_space.shape[-1]\n observation_space_dim = env.observation_space.shape[-1]\n\n # Instantiate agent and its policy\n policy = Policy(observation_space_dim, action_space_dim)\n policy.load_state_dict(params)\n agent = Agent(policy)\n\n test_reward, test_len = 0, 0\n for ep in range(episodes):\n done = False\n observation = env.reset()\n while not done:\n # Similar to the training loop above -\n # get the action, act on the environment, save total reward\n # (evaluation=True makes the agent always return what it thinks to be\n # the best action - there is no exploration at this point)\n action, _ = agent.get_action(observation, evaluation=True)\n observation, reward, done, info = env.step(action.detach().cpu().numpy())\n\n if render:\n env.render()\n test_reward += reward\n test_len += 1\n print(\"Average test reward:\", test_reward/episodes, \"episode length:\", test_len/episodes)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--test\", \"-t\", type=str, default=None, help=\"Model to be tested\")\n parser.add_argument(\"--env\", type=str, default=\"WimblepongVisualSimpleAI-v0\", help=\"Environment to use\")\n parser.add_argument(\"--train_episodes\", type=int, default=1000000, help=\"Number of episodes to train for\")\n parser.add_argument(\"--render_test\", action='store_true', help=\"Render test\")\n parser.add_argument('--prod-mode', type=lambda x:bool(strtobool(x)), default=True, nargs='?', const=True,\n help='run the script in production mode and use wandb to log outputs')\n parser.add_argument('--capture-video', type=lambda x:bool(strtobool(x)), default=True, nargs='?', const=True,\n help='weather to capture videos of the agent performances (check out `videos` folder)')\n parser.add_argument('--wandb-project-name', type=str, default=\"highway-env\",\n help=\"the wandb's project name\")\n parser.add_argument('--wandb-entity', type=str, default=None,\n help=\"the entity (team) of wandb's project\")\n args = parser.parse_args()\n\n # If no model was passed, train a policy from scratch.\n # Otherwise load the policy from the file and go directly to testing.\n if args.test is None:\n try:\n train(args.env, train_episodes=args.train_episodes)\n # Handle Ctrl+C - save model and go to tests\n except KeyboardInterrupt:\n print(\"Interrupted!\")\n else:\n state_dict = torch.load(args.test)\n print(\"Testing...\")\n policy.load_state_dict(state_dict)\n #test(args.env, 100, state_dict, args.render_test)\n"
] | [
[
"matplotlib.pyplot.legend",
"torch.load",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"torch.utils.tensorboard.SummaryWriter",
"matplotlib.pyplot.plot",
"numpy.array",
"numpy.mean"
]
] |
zhaotingchen/halomod | [
"0da45ac482f7d11cf3f6382bf19021e0344ecb7f"
] | [
"tests/test_integrate_corr.py"
] | [
"\"\"\"\nSimple tests for the integration scheme for ProjectedCF (thus far). Doesn't work\nas yet, since it tries to import the libraries from *this* folder, rather than\ninstallation (which doesn't work because the fortran code isn't installed.)\n\"\"\"\nimport inspect\nimport os\n\n#LOCATION = \"/\".join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))).split(\"/\")[:-1])\nimport sys\n#sys.path.insert(0, LOCATION)\nimport numpy as np\nfrom halomod import ProjectedCF\nfrom halomod.integrate_corr import projected_corr_gal\nfrom astropy.units import Mpc\nfrom mpmath import gamma,hyp2f1\n\nhyp2f1A = np.frompyfunc(lambda a,b,c,z: float(hyp2f1(a,b,c,z)), 4, 1)\n\ndef wprp_pl(rp,r0,g):\n return rp*(rp/r0)**-g * gamma(0.5)*gamma((g-1)/2.0)/gamma(g/2.0)\n\ndef wprp_pl_lim(rp,r0,g,rmax):\n return (1/gamma(g/2)) * (h.rp*h.rlim/r0)**-g * gamma((g-1)/2) * \\\n (gamma(0.5) * h.rp * h.rlim**g - h.rp**g *h.rlim * gamma(g/2)*\\\n hyp2f1A(0.5,(g-1)/2,(g+1)/2,h.rp.value**2/h.rlim.value**2))\n\nclass TestProjCorr():\n def __init__(self):\n self.rp = np.logspace(-2,1.2,50)\n self.gamma = 1.85 # Values from S1 sample of Beutler+2011\n self.r0 = 5.14\n\n self.wprp_anl = wprp_pl(self.rp,r0,g)\n self.wprp_anl_rlim = wprp_pl_lim(self.rp,r0,g,50.0)\n\n def test_auto_rlim(self):\n h = ProjectedCF(rp_min=self.rp) #This should imitate an \"infinite\" upper bound\n xir = (h.r.value/self.r0)**-self.gamma\n\n wprp_anl = wprp_pl(self.rp,self.r0,self.g)\n wprp = projected_corr_gal(h.r, xir, h.rlim, self.rp)\n assert np.all(abs(wprp-wprp_anl)/wprp_anl<0.01)\n\n def test_fixed_rlim(self):\n h = ProjectedCF(rp_min=self.rp,proj_limit=50.0)\n xir = (h.r.value/self.r0)**-self.gamma\n\n wprp_anl = wprp_pl_lim(self.rp,self.r0,self.g,50.0)\n wprp = projected_corr_gal(h.r, xir, h.rlim, self.rp)\n assert np.all(abs(wprp-wprp_anl)/wprp_anl<0.01)\n"
] | [
[
"numpy.logspace"
]
] |
martius-lab/SMORL | [
"d23eda9d6a72baa3ab1f4d729b2e4f742e4dd9db"
] | [
"rlkit/rlkit/torch/sac/policies.py"
] | [
"import numpy as np\nimport torch\nfrom torch import nn\n\nfrom rlkit.policies.base import ExplorationPolicy, Policy\nfrom rlkit.torch.core import eval_np\nfrom rlkit.torch.distributions import TanhNormal\nfrom rlkit.torch.networks import Mlp\nfrom rlkit.torch.modules import Attention, preprocess_attention_input\n\n\nLOG_SIG_MAX = 2\nLOG_SIG_MIN = -20\n\n\nclass TanhGaussianPolicy(Mlp, ExplorationPolicy):\n \"\"\"\n Usage:\n\n ```\n policy = TanhGaussianPolicy(...)\n action, mean, log_std, _ = policy(obs)\n action, mean, log_std, _ = policy(obs, deterministic=True)\n action, mean, log_std, log_prob = policy(obs, return_log_prob=True)\n ```\n\n Here, mean and log_std are the mean and log_std of the Gaussian that is\n sampled from.\n\n If deterministic is True, action = tanh(mean).\n If return_log_prob is False (default), log_prob = None\n This is done because computing the log_prob can be a bit expensive.\n \"\"\"\n def __init__(\n self,\n hidden_sizes,\n obs_dim,\n action_dim,\n std=None,\n init_w=1e-3,\n last_layer_init_w=None,\n last_layer_init_b=None,\n initial_log_std_offset=0,\n **kwargs\n ):\n super().__init__(\n hidden_sizes,\n input_size=obs_dim,\n output_size=action_dim,\n init_w=init_w,\n last_layer_init_w=last_layer_init_w,\n last_layer_init_b=last_layer_init_b,\n **kwargs\n )\n self.log_std = None\n self.std = std\n self.initial_log_std_offset = initial_log_std_offset\n if std is None:\n last_hidden_size = obs_dim\n if len(hidden_sizes) > 0:\n last_hidden_size = hidden_sizes[-1]\n self.last_fc_log_std = nn.Linear(last_hidden_size, action_dim)\n\n if last_layer_init_w is None:\n self.last_fc_log_std.weight.data.uniform_(-init_w, init_w)\n else:\n last_layer_init_w(self.last_fc_log_std.weight)\n\n if last_layer_init_b is None:\n self.last_fc_log_std.bias.data.uniform_(-init_w, init_w)\n else:\n last_layer_init_b(self.last_fc_log_std.bias)\n else:\n self.log_std = np.log(std)\n assert LOG_SIG_MIN <= self.log_std <= LOG_SIG_MAX\n\n def get_action(self, obs_np, deterministic=False):\n with torch.no_grad():\n actions = self.get_actions(obs_np[None],\n deterministic=deterministic)\n return actions[0, :], {}\n\n def get_actions(self, obs_np, deterministic=False):\n return eval_np(self, obs_np, deterministic=deterministic)[0]\n\n def forward(\n self,\n obs,\n reparameterize=True,\n deterministic=False,\n return_log_prob=False,\n ):\n \"\"\"\n :param obs: Observation\n :param deterministic: If True, do not sample\n :param return_log_prob: If True, return a sample and its log probability\n \"\"\"\n if self.normalizer is not None:\n obs = self.normalizer.normalize(obs)\n\n h = obs\n for i, fc in enumerate(self.fcs):\n h = self.hidden_activation(fc(h))\n mean = self.last_fc(h)\n if self.std is None:\n log_std = self.last_fc_log_std(h) + self.initial_log_std_offset\n log_std = torch.clamp(log_std, LOG_SIG_MIN, LOG_SIG_MAX)\n std = torch.exp(log_std)\n else:\n std = self.std\n log_std = self.log_std\n\n log_prob = None\n entropy = None\n mean_action_log_prob = None\n pre_tanh_value = None\n if deterministic:\n action = torch.tanh(mean)\n else:\n tanh_normal = TanhNormal(mean, std)\n if return_log_prob:\n if reparameterize is True:\n action, pre_tanh_value = tanh_normal.rsample(\n return_pretanh_value=True\n )\n else:\n action, pre_tanh_value = tanh_normal.sample(\n return_pretanh_value=True\n )\n log_prob = tanh_normal.log_prob(\n action,\n pre_tanh_value=pre_tanh_value\n )\n log_prob = log_prob.sum(dim=1, keepdim=True)\n else:\n if reparameterize is True:\n action = tanh_normal.rsample()\n else:\n action = tanh_normal.sample()\n\n return (\n action, mean, log_std, log_prob, entropy, std,\n mean_action_log_prob, pre_tanh_value,\n )\n\n\nclass MakeDeterministic(nn.Module, Policy):\n def __init__(self, stochastic_policy):\n super().__init__()\n self.stochastic_policy = stochastic_policy\n\n def get_action(self, observation):\n return self.stochastic_policy.get_action(observation,\n deterministic=True)\n\n def to(self, device):\n super().to(device)\n self.stochastic_policy.to(device)\n\n\nclass AttentionTanhGaussianPolicy(TanhGaussianPolicy):\n \"\"\"\n Usage:\n\n ```\n policy = TanhGaussianPolicy(...)\n action, mean, log_std, _ = policy(obs)\n action, mean, log_std, _ = policy(obs, deterministic=True)\n action, mean, log_std, log_prob = policy(obs, return_log_prob=True)\n ```\n\n Here, mean and log_std are the mean and log_std of the Gaussian that is\n sampled from.\n\n If deterministic is True, action = tanh(mean).\n If return_log_prob is False (default), log_prob = None\n This is done because computing the log_prob can be a bit expensive.\n \"\"\"\n def __init__(self,\n hidden_sizes,\n embed_dim,\n z_size,\n max_objects,\n z_goal_size,\n action_dim,\n std=None,\n init_w=1e-3,\n n_frames=None,\n attention_kwargs=None,\n **kwargs):\n if attention_kwargs is None:\n attention_kwargs = {}\n attention = Attention(embed_dim, z_goal_size, z_size,\n **attention_kwargs)\n\n super().__init__(hidden_sizes,\n attention.output_dim + attention.embed_dim,\n action_dim,\n std,\n init_w,\n **kwargs)\n\n self.z_goal_size = z_goal_size\n self.z_size = z_size\n self.n_frames = n_frames\n\n self.attention = attention\n\n def forward(self, obs,\n reparameterize=True,\n deterministic=False,\n return_log_prob=False):\n \"\"\"\n :param obs: Observation\n :param deterministic: If True, do not sample\n :param return_log_prob: If True, return a sample and its log probability\n \"\"\"\n x, g, n_objects = preprocess_attention_input(obs,\n self.z_size,\n self.z_goal_size,\n self.n_frames)\n goal_embedding = self.attention.embed(g)\n state_embedding = self.attention.embed(x)\n\n h = self.attention.forward(state_embedding, goal_embedding, n_objects)\n\n return super().forward(torch.cat((h, goal_embedding.squeeze(1)), dim=1),\n reparameterize=reparameterize,\n deterministic=deterministic,\n return_log_prob=return_log_prob)\n\n def to(self, device):\n super().to(device)\n self.attention.to(device)\n\n\nclass DeepSetTanhGaussianPolicy(TanhGaussianPolicy):\n def __init__(self,\n hidden_sizes,\n key_query_size, # unused\n z_size,\n max_objects,\n z_goal_size,\n value_size, # unused\n action_dim,\n embed_dim,\n aggregation_dim,\n std=None,\n init_w=1e-3,\n n_frames=None,\n **kwargs):\n super().__init__(hidden_sizes,\n aggregation_dim + embed_dim,\n action_dim,\n std,\n init_w,\n **kwargs)\n self.z_goal_size = z_goal_size\n self.z_size = z_size\n self.n_frames = n_frames\n\n self.embedding = nn.Linear(z_size, embed_dim)\n self.pre_aggregation = nn.Sequential(nn.Linear(embed_dim,\n aggregation_dim),\n nn.ReLU(),\n nn.Linear(aggregation_dim,\n aggregation_dim))\n for layer in (self.embedding,\n self.pre_aggregation[0],\n self.pre_aggregation[2]):\n if 'hidden_init' in kwargs:\n kwargs['hidden_init'](layer.weight)\n nn.init.zeros_(layer.bias)\n\n def forward(self, obs,\n reparameterize=True,\n deterministic=False,\n return_log_prob=False):\n \"\"\"\n :param obs: Observation\n :param deterministic: If True, do not sample\n :param return_log_prob: If True, return a sample and its log probability\n \"\"\"\n x, g, n_objects = preprocess_attention_input(obs,\n self.z_size,\n self.z_goal_size,\n self.n_frames)\n goal_embedding = self.embedding(g)\n state_embedding = self.embedding(x)\n\n h = self.pre_aggregation(state_embedding).sum(dim=1)\n\n return super().forward(torch.cat((h, goal_embedding.squeeze(1)), dim=1),\n reparameterize=reparameterize,\n deterministic=deterministic,\n return_log_prob=return_log_prob)\n\n def to(self, device):\n super().to(device)\n"
] | [
[
"torch.nn.Linear",
"torch.no_grad",
"torch.exp",
"numpy.log",
"torch.tanh",
"torch.nn.init.zeros_",
"torch.nn.ReLU",
"torch.clamp"
]
] |
LeonardoESousa/xcharge | [
"89342cd6ad00d7a767ed8e058a3ee8037af5e52f"
] | [
"kmc/rates.py"
] | [
"\nimport numpy as np\nimport random\nfrom kmc.particles import *\n\nepsilon_vaccum = 8.854187e-12 #Permitivity in C/Vm\ne = -1.60217662e-19 #Electron charge \nkb = 8.617e-5 #Boltzmann constant\nhbar = 6.582e-16 #Reduced Planck's constant\n\n\n\n###RATES################################################################################# \n\n##FUNCTION FOR SETTING RADII#############################################################\ndef raios(num,Rf,mat,lifetime,mats):\n Raios = np.empty(num)\n Raios.fill(Rf[(mat,mat)])\n materiais = [i for i in lifetime.keys() if i != mat]\n for m in materiais:\n Raios[mats == m] = Rf[(mat,m)]\n return Raios\n\ndef raios_dist(num,Rf,mat,lifetime,mats):\n Raios = np.array(random.choices(Rf[(mat,mat)][:,0],Rf[(mat,mat)][:,1],k=num))\n materiais = [i for i in lifetime.keys() if i != mat]\n for m in materiais:\n R2 = np.array(random.choices(Rf[(mat,m)][:,0],Rf[(mat,m)][:,1],k=num))\n Raios[mats == m] = R2[mats == m]\n return Raios\n\n\n#########################################################################################\n\n##STANDARD FORSTER TRANSFER RATE#########################################################\nclass Forster:\n def __init__(self,**kwargs):\n self.kind = 'jump'\n self.Rf = kwargs['Rf']\n self.lifetime = kwargs['life']\n self.mu = kwargs['mu']\n self.alpha = 1.15*0.53\n\n\n def rate(self,**kwargs):\n r = kwargs['r']\n system = kwargs['system']\n ex = kwargs['particle']\n mats = system.mats \n local = ex.position \n mat = mats[local]\n \n Rf = raios(len(mats),self.Rf,mat,self.lifetime,mats)\n \n x = (Rf/(self.alpha*self.mu[mat] + r))\n taxa = (1/self.lifetime[mat])*x*x*x*x*x*x\n taxa[r == 0] = 0\n return taxa\n\n\n def action(self,particle,system,local):\n particle.move(local)\n#########################################################################################\n\n##TRIPLET TO SINGLET FORSTER TRANSFER####################################################\nclass ForsterT:\n def __init__(self,**kwargs):\n self.kind = 'jump'\n self.Rf = kwargs['Rf']\n self.lifetime = kwargs['life']\n self.mu = kwargs['mu']\n self.alpha = 1.15*0.53\n\n def rate(self,**kwargs):\n r = kwargs['r']\n system = kwargs['system']\n ex = kwargs['particle']\n mats = system.mats \n local = ex.position \n mat = mats[local]\n \n Rf = raios(len(mats),self.Rf,mat,self.lifetime,mats)\n x = (Rf/(self.alpha*self.mu[mat] + r))\n taxa = (1/self.lifetime[mat])*x*x*x*x*x*x\n taxa[r == 0] = 0\n return taxa\n\n def action(self,particle,system,local):\n particle.move(local)\n particle.kill('tts',system,system.t1,'converted')\n system.set_particles([Singlet(local)])\n#########################################################################################\n\n##FORSTER TRANSFER WITH ORIENTATION FACTORS ON THE FLY###################################\nclass ForsterKappa:\n def __init__(self,**kwargs):\n self.kind = 'jump'\n self.Rf = kwargs['Rf']\n self.lifetime = kwargs['life']\n self.mu = kwargs['mu']\n self.alpha = 1.15*0.53\n\n def rate(self,**kwargs):\n r = kwargs['r']\n system = kwargs['system']\n ex = kwargs['particle']\n mats = system.mats \n local = ex.position \n mat = mats[local]\n mus = np.copy(system.mu)\n\n R = np.copy(system.R) \n dR = R - R[local,:]\n modulo = np.sqrt(np.sum(dR*dR,axis=1))[:,np.newaxis]\n dR /= modulo\n\n kappa = np.inner(mus[local,:],mus) - 3*(np.inner(mus[local,:],dR)*(np.sum(mus*dR,axis=1))) \n Rf = raios(len(mats),self.Rf,mat,self.lifetime,mats)\n \n x = (Rf/(self.alpha*system.norma_mu[local] + r))\n taxa = (1/self.lifetime[mat])*(kappa*kappa)*x*x*x*x*x*x\n taxa[r == 0] = 0\n return taxa\n\n def action(self,particle,system,local):\n particle.move(local)\n#########################################################################################\n\n##STANDARD FORSTER TRANSFER RATE#########################################################\nclass ForsterRedShift:\n def __init__(self,**kwargs):\n self.kind = 'jump'\n self.Rf = kwargs['Rf']\n self.lifetime = kwargs['life']\n self.mu = kwargs['mu']\n self.T = kwargs['T']\n self.alpha = 1.15*0.53\n\n\n def rate(self,**kwargs):\n r = kwargs['r']\n system = kwargs['system']\n ex = kwargs['particle']\n mats = system.mats \n local = ex.position \n mat = mats[local]\n num = len(mats)\n \n Rfs = raios_dist(num,self.Rf,mat,self.lifetime,mats)\n \n s1s = np.copy(system.s1)\n s1s = (s1s - s1s[local]) + abs(s1s - s1s[local]) \n boltz = np.exp(-1*s1s/(2*kb*self.T)) \n x = Rfs/(self.alpha*self.mu[mat] + r)\n taxa = (1/self.lifetime[mat])*x*x*x*x*x*x*boltz\n taxa[r == 0] = 0\n return taxa\n\n\n def action(self,particle,system,local):\n particle.move(local)\n#########################################################################################\n\n##STANDARD DEXTER TRANSFER RATE##########################################################\nclass Dexter:\n def __init__(self,**kwargs):\n self.kind = 'jump'\n self.Rd = kwargs['Rd']\n self.lifetime = kwargs['life']\n self.L = kwargs['L']\n \n def rate(self,**kwargs):\n r = kwargs['r']\n system = kwargs['system']\n ex = kwargs['particle']\n mats = system.mats \n local = ex.position \n mat = mats[local]\n \n Rd = raios(len(mats),self.Rd,mat,self.lifetime,mats)\n \n taxa = (1/self.lifetime[mat])*np.exp((2*Rd/self.L[mat])*(1-r/Rd))\n taxa[r == 0] = 0\n return taxa\n\n def action(self,particle,system,local):\n particle.move(local)\n######################################################################################### \n\n##EXCITON DISSOCIATION BY ELECTRON HOP RATE##############################################\nclass Dissociation_electron:\n def __init__(self,**kwargs):\n self.kind = 'dissociation_e'\n self.AtH = kwargs['AtH']\n self.inv = kwargs['invrad']\n self.T = kwargs['T']\n\n def rate(self,**kwargs):\n system = kwargs['system']\n r = kwargs['r']\n particle = kwargs['particle']\n local = particle.position \n mats = system.mats \n mat = mats[local]\n num = len(mats)\n\n lumos = np.copy(system.lumo)\n homos = np.copy(system.homo)\n if particle.species == 'singlet':\n s1s = np.copy(system.s1) \n elif particle.species == 'triplet':\n s1s = np.copy(system.t1)\n\n AtH = raios(num,self.AtH,mat,self.inv,mats)\n in_loc_rad = self.inv[mat]\n \n DEe = lumos - (homos[local] + s1s[local])\n taxae = (1e-12)*(AtH)*np.exp(-2*in_loc_rad*r)*np.exp(-(DEe+abs(DEe))/(2*kb*self.T))\n taxae[r == 0] = 0\n return taxae\n \n \n def action(self,particle,system,local):\n e = Electron(local)\n h = Hole(particle.position)\n h.identity = -1*e.identity \n system.set_particles([e,h])\n particle.kill(self.kind,system,system.s1,'converted')\n#########################################################################################\n\n##EXCITON DISSOCIATION BY HOLE HOP RATE##################################################\nclass Dissociation_hole:\n def __init__(self,**kwargs):\n self.kind = 'dissociation_h'\n self.AtH = kwargs['AtH']\n self.inv = kwargs['invrad']\n self.T = kwargs['T']\n\n def rate(self,**kwargs):\n system = kwargs['system']\n r = kwargs['r']\n particle = kwargs['particle']\n local = particle.position \n mats = system.mats \n mat = mats[local]\n num = len(mats)\n\n lumos = np.copy(system.lumo)\n homos = np.copy(system.homo)\n if particle.species == 'singlet':\n s1s = np.copy(system.s1) \n elif particle.species == 'triplet':\n s1s = np.copy(system.t1)\n\n AtH = raios(num,self.AtH,mat,self.inv,mats)\n in_loc_rad = self.inv[mat]\n \n DEh = (lumos[local] - s1s[local]) - homos \n taxah = (1e-12)*(AtH)*np.exp(-2*in_loc_rad*r)*np.exp(-(DEh+abs(DEh))/(2*kb*self.T))\n taxah[r == 0] = 0\n return taxah\n \n def action(self,particle,system,local):\n e = Electron(particle.position)\n h = Hole(local) \n h.identity = -1*e.identity \n system.set_particles([e,h])\n particle.kill(self.kind,system,system.s1,'converted')\n#########################################################################################\n\n\ndef corrected_energies(system,s,r):\n potential = np.copy(system.electrostatic())\n r[r == 0] = np.inf \n potential -= s.charge*abs(e)/(4*np.pi*system.epsilon*r)\n indices_e = np.array([x.position for x in system.particles if x.charge == -1 and x.position != s.position]).astype(int)\n indices_h = np.array([x.position for x in system.particles if x.charge == 1 and x.position != s.position]).astype(int)\n\n if s.species == 'electron':\n engs = np.copy(system.lumo)\n engs[indices_h] = system.homo[indices_h]\n engs[indices_e] = np.inf \n engs += -1*potential\n DE = (engs - engs[s.position]) + abs(engs - engs[s.position])\n elif s.species == 'hole':\n engs = np.copy(system.homo)\n engs[indices_e] = system.lumo[indices_e] \n engs[indices_h] = -np.inf \n engs += -1*potential\n DE = (engs[s.position] - engs) + abs(engs[s.position] - engs)\n return DE\n\n\n\n##MILLER-ABRHAMS RATE####################################################################\nclass MillerAbrahams:\n def __init__(self,**kwargs):\n self.kind = 'miller-abrahams'\n self.AtH = kwargs['AtH']\n self.inv = kwargs['invrad']\n self.T = kwargs['T']\n\n def rate(self,**kwargs):\n system = kwargs['system']\n r = kwargs['r']\n particle = kwargs['particle']\n mats = system.mats \n mat = mats[particle.position]\n \n AtH = raios(len(r),self.AtH,mat,self.inv,mats)\n in_loc_rad = self.inv[mat]\n\n DE = corrected_energies(system,particle,r) \n taxa = (1e-12)*(AtH)*np.exp(\n -(in_loc_rad*r+in_loc_rad*r))*np.exp(-DE/((kb*self.T+kb*self.T))) \t \n taxa[r == 0] = 0\n return taxa\n \n def action(self,particle,system,local):\n particle.move(local)\n\n######################################################################################### \n\n\n\n#MONOMOLECULAR RATES#####################################################################\n\n##FLUORESCENCE RATE######################################################################\nclass Fluor:\n def __init__(self,**kwargs):\n self.kind = 'fluor'\n self.lifetime = kwargs['life']\n\n def rate(self,**kwargs):\n return 1/self.lifetime[kwargs['material']]\n \n def action(self,particle,system,local):\n particle.kill(self.kind,system,system.s1,'dead') \n#########################################################################################\n\n##PHOSPHORESCENCE RATE###################################################################\nclass Phosph:\n def __init__(self,**kwargs):\n self.kind = 'phosph'\n self.lifetime = kwargs['life']\n\n def rate(self,**kwargs):\n return 1/self.lifetime[kwargs['material']]\n \n def action(self,particle,system,local):\n particle.kill(self.kind,system,system.t1,'dead')\n#########################################################################################\n \n##NONRADIATIVE DECAY RATE################################################################ \nclass Nonrad:\n def __init__(self,**kwargs):\n self.kind = 'nonrad'\n self.taxa = kwargs['rate']\n\n def rate(self,**kwargs):\n return self.taxa[kwargs['material']]\n \n def action(self,particle,system,local):\n particle.kill(self.kind,system,system.s1,'dead') \n#########################################################################################\n\n##INTERSYSTEM CROSSING RATE##############################################################\nclass ISC:\n def __init__(self,**kwargs):\n self.kind = 'isc'\n self.taxa = kwargs['rate']\n self.map = {'singlet':'triplet', 'triplet':'singlet'}\n\n def rate(self,**kwargs):\n material = kwargs['material']\n return self.taxa[material]\n \n def action(self,particle,system,local):\n if particle.species == 'singlet':\n system.set_particles([Triplet(particle.position)])\n particle.kill(self.kind,system,system.s1,'converted')\n elif particle.species == 'triplet': \n system.set_particles([Singlet(particle.position)])\n particle.kill('r'+self.kind,system,system.s1,'converted')\n#########################################################################################\n\n\n"
] | [
[
"numpy.sum",
"numpy.empty",
"numpy.exp",
"numpy.copy",
"numpy.array",
"numpy.inner"
]
] |
nvzhou/DeepRec-1 | [
"d69d6a4c27434dbec8c295b98aefcd7912908d4b"
] | [
"modelzoo/DIEN/train.py"
] | [
"import time\nimport argparse\nimport tensorflow as tf\nimport os\nimport sys\nimport math\nimport collections\nfrom tensorflow.python.client import timeline\nimport json\n\nfrom tensorflow.python.ops import partitioned_variables\n\nfrom tensorflow.contrib.rnn.python.ops.core_rnn_cell import _Linear\nfrom tensorflow.python.feature_column.feature_column import _LazyBuilder\nfrom tensorflow.python.feature_column import utils as fc_utils\n\n# Set to INFO for tracking training, default is WARN. ERROR for least messages\ntf.logging.set_verbosity(tf.logging.INFO)\nprint(\"Using TensorFlow version %s\" % (tf.__version__))\n\nUNSEQ_COLUMNS = ['UID', 'ITEM', 'CATEGORY']\nHIS_COLUMNS = ['HISTORY_ITEM', 'HISTORY_CATEGORY']\nNEG_COLUMNS = ['NOCLK_HISTORY_ITEM', 'NOCLK_HISTORY_CATEGORY']\nSEQ_COLUMNS = HIS_COLUMNS + NEG_COLUMNS\nLABEL_COLUMN = [\"CLICKED\"]\nTRAIN_DATA_COLUMNS = LABEL_COLUMN + UNSEQ_COLUMNS + SEQ_COLUMNS\n\nEMBEDDING_DIM = 18\nHIDDEN_SIZE = 18 * 2\nATTENTION_SIZE = 18 * 2\nMAX_SEQ_LENGTH = 50\n\n\ndef add_layer_summary(value, tag):\n tf.summary.scalar('%s/fraction_of_zero_values' % tag,\n tf.nn.zero_fraction(value))\n tf.summary.histogram('%s/activation' % tag, value)\n\n\ndef _assert_all_equal_and_return(tensors, name=None):\n \"\"\"Asserts that all tensors are equal and returns the first one.\"\"\"\n with tf.name_scope(name, 'assert_all_equal', values=tensors):\n if len(tensors) == 1:\n return tensors[0]\n assert_equal_ops = []\n for t in tensors[1:]:\n assert_equal_ops.append(tf.debugging.assert_equal(tensors[0], t))\n with tf.control_dependencies(assert_equal_ops):\n return tf.identity(tensors[0])\n\n\ndef generate_input_data(filename, batch_size, num_epochs):\n def parse_csv(value, neg_value):\n tf.logging.info('Parsing {}'.format(filename))\n cate_defaults = [[\" \"] for i in range(0, 5)]\n # cate_defaults = [[\" \"] for i in range(0, 7)]\n label_defaults = [[0]]\n column_headers = TRAIN_DATA_COLUMNS\n record_defaults = label_defaults + cate_defaults\n columns = tf.io.decode_csv(value,\n record_defaults=record_defaults,\n field_delim='\\t')\n neg_columns = tf.io.decode_csv(neg_value,\n record_defaults=[[\"\"], [\"\"]],\n field_delim='\\t')\n columns.extend(neg_columns)\n all_columns = collections.OrderedDict(zip(column_headers, columns))\n\n labels = all_columns.pop(LABEL_COLUMN[0])\n features = all_columns\n return features, labels\n\n # Extract lines from input files using the Dataset API.\n dataset = tf.data.TextLineDataset(filename)\n dataset_neg_samples = tf.data.TextLineDataset(filename + '_neg')\n dataset = tf.data.Dataset.zip((dataset, dataset_neg_samples))\n dataset = dataset.shuffle(buffer_size=20000,\n seed=2021) # set seed for reproducing\n dataset = dataset.repeat(num_epochs)\n dataset = dataset.prefetch(batch_size)\n dataset = dataset.batch(batch_size)\n dataset = dataset.map(parse_csv,\n num_parallel_calls=tf.data.experimental.AUTOTUNE)\n dataset = dataset.prefetch(1)\n return dataset\n\n\ndef build_feature_cols(data_location=None):\n # uid_file\n uid_file = os.path.join(data_location, 'uid_voc.txt')\n mid_file = os.path.join(data_location, 'mid_voc.txt')\n cat_file = os.path.join(data_location, 'cat_voc.txt')\n if (not os.path.exists(uid_file)) or (not os.path.exists(mid_file)) or (\n not os.path.exists(cat_file)):\n print(\n \"uid_voc.txt, mid_voc.txt or cat_voc does not exist in data file.\")\n sys.exit()\n # uid\n uid_cate_column = tf.feature_column.categorical_column_with_vocabulary_file(\n 'UID', uid_file, default_value=0)\n uid_emb_column = tf.feature_column.embedding_column(\n uid_cate_column, dimension=EMBEDDING_DIM)\n\n # item\n item_cate_column = tf.feature_column.categorical_column_with_vocabulary_file(\n 'ITEM', mid_file, default_value=0)\n category_cate_column = tf.feature_column.categorical_column_with_vocabulary_file(\n 'CATEGORY', cat_file, default_value=0)\n\n # history behavior\n his_item_cate_column = tf.feature_column.sequence_categorical_column_with_vocabulary_file(\n 'HISTORY_ITEM', mid_file, default_value=0)\n his_category_cate_column = tf.feature_column.sequence_categorical_column_with_vocabulary_file(\n 'HISTORY_CATEGORY', cat_file, default_value=0)\n\n # negative samples\n noclk_his_item_cate_column = tf.feature_column.sequence_categorical_column_with_vocabulary_file(\n 'NOCLK_HISTORY_ITEM', mid_file, default_value=0)\n noclk_his_category_cate_column = tf.feature_column.sequence_categorical_column_with_vocabulary_file(\n 'NOCLK_HISTORY_CATEGORY', cat_file, default_value=0)\n\n return {\n 'uid_emb_column': uid_emb_column,\n 'item_cate_column': item_cate_column,\n 'category_cate_column': category_cate_column,\n 'his_item_cate_column': his_item_cate_column,\n 'his_category_cate_column': his_category_cate_column,\n 'noclk_his_item_cate_column': noclk_his_item_cate_column,\n 'noclk_his_category_cate_column': noclk_his_category_cate_column\n }\n\n\nclass VecAttGRUCell(tf.nn.rnn_cell.RNNCell):\n def __init__(self,\n num_units,\n activation=None,\n reuse=None,\n kernel_initializer=None,\n bias_initializer=None):\n super(VecAttGRUCell, self).__init__(_reuse=reuse)\n self._num_units = num_units\n self._activation = activation or tf.math.tanh\n self._kernel_initializer = kernel_initializer\n self._bias_initializer = bias_initializer\n self._gate_linear = None\n self._candidate_linear = None\n\n @property\n def state_size(self):\n return self._num_units\n\n @property\n def output_size(self):\n return self._num_units\n\n def __call__(self, inputs, state):\n return self.call(inputs, state)\n\n def call(self, inputs, state, att_score=None):\n \"\"\"Gated recurrent unit (GRU) with nunits cells.\"\"\"\n _inputs = inputs[0]\n att_score = inputs[1]\n if self._gate_linear is None:\n bias_ones = self._bias_initializer\n if self._bias_initializer is None:\n bias_ones = tf.constant_initializer(1.0, dtype=_inputs.dtype)\n with tf.variable_scope(\"gates\"): # Reset gate and update gate.\n self._gate_linear = _Linear(\n [_inputs, state],\n 2 * self._num_units,\n True,\n bias_initializer=bias_ones,\n kernel_initializer=self._kernel_initializer)\n\n value = tf.math.sigmoid(self._gate_linear([_inputs, state]))\n r, u = tf.split(value=value, num_or_size_splits=2, axis=1)\n\n r_state = r * state\n if self._candidate_linear is None:\n with tf.variable_scope(\"candidate\"):\n self._candidate_linear = _Linear(\n [_inputs, r_state],\n self._num_units,\n True,\n bias_initializer=self._bias_initializer,\n kernel_initializer=self._kernel_initializer)\n c = self._activation(self._candidate_linear([_inputs, r_state]))\n u = (1.0 - att_score) * u\n new_h = u * state + (1 - u) * c\n return new_h, new_h\n\n\nclass DIEN():\n def __init__(self,\n feature_column=None,\n learning_rate=0.001,\n embedding_dim=18,\n hidden_size=36,\n attention_size=36,\n inputs=None,\n bf16=False,\n input_layer_partitioner=None,\n dense_layer_partitioner=None):\n if not inputs:\n raise ValueError('Dataset is not defined.')\n if not feature_column:\n raise ValueError('Dense column or sparse column is not defined.')\n # self.feature_column = feature_column\n self.uid_emb_column = feature_column['uid_emb_column']\n self.item_cate_column = feature_column['item_cate_column']\n self.his_item_cate_column = feature_column['his_item_cate_column']\n self.category_cate_column = feature_column['category_cate_column']\n self.his_category_cate_column = feature_column[\n 'his_category_cate_column']\n self.noclk_his_item_cate_column = feature_column[\n 'noclk_his_item_cate_column']\n self.noclk_his_category_cate_column = feature_column[\n 'noclk_his_category_cate_column']\n\n self.learning_rate = learning_rate\n self.input_layer_partitioner = input_layer_partitioner\n self.dense_layer_partitioner = dense_layer_partitioner\n\n self.feature = inputs[0]\n self.label = inputs[1]\n self.batch_size = tf.shape(self.label)[0]\n self.embedding_dim = embedding_dim\n self.hidden_size = hidden_size\n self.attention_size = attention_size\n self.bf16 = bf16\n if self.bf16:\n self.data_tpye = tf.bfloat16\n else:\n self.data_tpye = tf.float32\n\n self.predict = self.prediction()\n with tf.name_scope('head'):\n self.train_op, self.loss = self.optimizer()\n self.acc, self.acc_op = tf.metrics.accuracy(labels=self.label,\n predictions=tf.round(\n self.predict))\n self.auc, self.auc_op = tf.metrics.auc(labels=self.label,\n predictions=self.predict,\n num_thresholds=1000)\n tf.summary.scalar('eval_acc', self.acc)\n tf.summary.scalar('eval_auc', self.auc)\n\n def prelu(self, x, scope=''):\n \"\"\"parametric ReLU activation\"\"\"\n with tf.variable_scope(name_or_scope=scope, default_name=\"prelu\"):\n alpha = tf.get_variable(\"prelu_\" + scope,\n shape=x.get_shape()[-1],\n dtype=x.dtype,\n initializer=tf.constant_initializer(0.1))\n pos = tf.nn.relu(x)\n neg = alpha * (x - abs(x)) * tf.constant(0.5, dtype=x.dtype)\n return pos + neg\n\n def auxiliary_net(self, in_, stag='auxiliary_net'):\n bn1 = tf.layers.batch_normalization(inputs=in_,\n name='bn1' + stag,\n reuse=tf.AUTO_REUSE)\n dnn1 = tf.layers.dense(bn1,\n 100,\n activation=None,\n name='f1' + stag,\n reuse=tf.AUTO_REUSE)\n dnn1 = tf.nn.sigmoid(dnn1)\n dnn2 = tf.layers.dense(dnn1,\n 50,\n activation=None,\n name='f2' + stag,\n reuse=tf.AUTO_REUSE)\n dnn2 = tf.nn.sigmoid(dnn2)\n dnn3 = tf.layers.dense(dnn2,\n 2,\n activation=None,\n name='f3' + stag,\n reuse=tf.AUTO_REUSE)\n y_hat = tf.nn.softmax(dnn3) + tf.constant(0.00000001, dtype=dnn3.dtype)\n return y_hat\n\n def auxiliary_loss(self,\n h_states,\n click_seq,\n noclick_seq,\n mask,\n dtype=tf.float32,\n stag=None):\n mask = tf.cast(mask, dtype=dtype)\n click_input_ = tf.concat([h_states, click_seq], -1)\n noclick_input_ = tf.concat([h_states, noclick_seq], -1)\n if dtype == tf.bfloat16:\n with tf.variable_scope('auxiliary_net').keep_weights(dtype=tf.float32):\n click_prop_ = self.auxiliary_net(click_input_, stag=stag)[:, :,\n 0]\n noclick_prop_ = self.auxiliary_net(noclick_input_,\n stag=stag)[:, :, 0]\n else:\n\n with tf.variable_scope('auxiliary_net'):\n click_prop_ = self.auxiliary_net(click_input_, stag=stag)[:, :,\n 0]\n noclick_prop_ = self.auxiliary_net(noclick_input_,\n stag=stag)[:, :, 0]\n\n click_loss_ = -tf.reshape(tf.log(click_prop_),\n [-1, tf.shape(click_seq)[1]]) * mask\n noclick_loss_ = -tf.reshape(tf.log(1.0 - noclick_prop_),\n [-1, tf.shape(noclick_seq)[1]]) * mask\n loss_ = tf.reduce_mean(click_loss_ + noclick_loss_)\n return loss_\n\n def attention(self,\n query,\n facts,\n attention_size,\n mask,\n stag='null',\n mode='SUM',\n softmax_stag=1,\n time_major=False,\n return_alphas=False,\n forCnn=False):\n if isinstance(facts, tuple):\n # In case of Bi-RNN, concatenate the forward and the backward RNN outputs.\n facts = tf.concat(facts, 2)\n if len(facts.get_shape().as_list()) == 2:\n facts = tf.expand_dims(facts, 1)\n\n if time_major:\n # (T,B,D) => (B,T,D)\n facts = tf.array_ops.transpose(facts, [1, 0, 2])\n # Trainable parameters\n # mask = tf.equal(mask, tf.ones_like(mask))\n facts_size = facts.get_shape().as_list()[\n -1] # D value - hidden size of the RNN layer\n querry_size = query.get_shape().as_list()[-1]\n query = tf.layers.dense(query,\n facts_size,\n activation=None,\n name='f1' + stag)\n query = self.prelu(query)\n queries = tf.tile(query, [1, tf.shape(facts)[1]])\n queries = tf.reshape(queries, tf.shape(facts))\n din_all = tf.concat([queries, facts, queries - facts, queries * facts],\n axis=-1)\n d_layer_1_all = tf.layers.dense(din_all,\n 80,\n activation=tf.nn.sigmoid,\n name='f1_att' + stag)\n d_layer_2_all = tf.layers.dense(d_layer_1_all,\n 40,\n activation=tf.nn.sigmoid,\n name='f2_att' + stag)\n d_layer_3_all = tf.layers.dense(d_layer_2_all,\n 1,\n activation=None,\n name='f3_att' + stag)\n d_layer_3_all = tf.reshape(d_layer_3_all, [-1, 1, tf.shape(facts)[1]])\n scores = d_layer_3_all\n # Mask\n # key_masks = tf.sequence_mask(facts_length, tf.shape(facts)[1]) # [B, T]\n key_masks = tf.expand_dims(mask, 1) # [B, 1, T]\n paddings = tf.ones_like(scores) * (-2**32 + 1)\n if not forCnn:\n scores = tf.where(key_masks, scores, paddings) # [B, 1, T]\n\n # Scale\n # scores = scores / (facts.get_shape().as_list()[-1] ** 0.5)\n\n # Activation\n if softmax_stag:\n scores = tf.nn.softmax(scores) # [B, 1, T]\n\n # Weighted sum\n if mode == 'SUM':\n output = tf.matmul(scores, facts) # [B, 1, H]\n # output = tf.reshape(output, [-1, tf.shape(facts)[-1]])\n else:\n scores = tf.reshape(scores, [-1, tf.shape(facts)[1]])\n output = facts * tf.expand_dims(scores, -1)\n output = tf.reshape(output, tf.shape(facts))\n if return_alphas:\n return output, scores\n return output\n\n def dice(self, _x, axis=-1, epsilon=0.000000001, name=''):\n with tf.variable_scope(name, reuse=tf.AUTO_REUSE):\n alphas = tf.get_variable('alpha' + name,\n _x.get_shape()[-1],\n initializer=tf.constant_initializer(0.0),\n dtype=_x.dtype)\n input_shape = list(_x.get_shape())\n\n reduction_axes = list(range(len(input_shape)))\n del reduction_axes[axis]\n broadcast_shape = [1] * len(input_shape)\n broadcast_shape[axis] = input_shape[axis]\n\n # case: train mode (uses stats of the current batch)\n mean = tf.reduce_mean(_x, axis=reduction_axes)\n brodcast_mean = tf.reshape(mean, broadcast_shape)\n std = tf.reduce_mean(tf.square(_x - brodcast_mean) + epsilon,\n axis=reduction_axes)\n std = tf.sqrt(std)\n brodcast_std = tf.reshape(std, broadcast_shape)\n x_normed = (_x - brodcast_mean) / (brodcast_std + epsilon)\n # x_normed = tf.layers.batch_normalization(_x, center=False, scale=False)\n x_p = tf.sigmoid(x_normed)\n\n return alphas * (1.0 - x_p) * _x + x_p * _x\n\n def embedding_input_layer(self,\n builder,\n feature_column,\n embedding_table,\n get_seq_len=False):\n sparse_tensors = feature_column._get_sparse_tensors(builder)\n sparse_tensors_ids = sparse_tensors.id_tensor\n sparse_tensors_weights = sparse_tensors.weight_tensor\n\n embedding = tf.nn.safe_embedding_lookup_sparse(\n embedding_weights=embedding_table,\n sparse_ids=sparse_tensors_ids,\n sparse_weights=sparse_tensors_weights)\n\n if get_seq_len:\n sequence_length = fc_utils.sequence_length_from_sparse_tensor(\n sparse_tensors_ids)\n return embedding, sequence_length\n else:\n return embedding\n\n def embedding_input(self):\n for key in [\n 'HISTORY_ITEM', 'HISTORY_CATEGORY', 'NOCLK_HISTORY_ITEM',\n 'NOCLK_HISTORY_CATEGORY'\n ]:\n self.feature[key] = tf.strings.split(self.feature[key], '\u0002')\n self.feature[key] = tf.sparse.slice(\n self.feature[key], [0, 0], [self.batch_size, MAX_SEQ_LENGTH])\n\n # get uid embeddings\n uid_emb = tf.feature_column.input_layer(self.feature,\n self.uid_emb_column)\n # get embeddings of item and category\n # create embedding table\n item_embedding_var = tf.get_variable(\n 'item_embedding_var',\n [self.item_cate_column._num_buckets, self.embedding_dim])\n category_embedding_var = tf.get_variable(\n 'category_embedding_var',\n [self.category_cate_column._num_buckets, self.embedding_dim])\n\n builder = _LazyBuilder(self.feature)\n # get item embedding concat [item_id,category]\n item_embedding = self.embedding_input_layer(builder,\n self.item_cate_column,\n item_embedding_var)\n category_embedding = self.embedding_input_layer(\n builder, self.category_cate_column, category_embedding_var)\n item_emb = tf.concat([item_embedding, category_embedding], 1)\n\n # get history item embedding concat [history_item_id,history_category] and sequence length\n his_item_embedding, his_item_sequence_length = self.embedding_input_layer(\n builder,\n self.his_item_cate_column,\n item_embedding_var,\n get_seq_len=True)\n his_category_embedding, his_category_sequence_length = self.embedding_input_layer(\n builder,\n self.his_category_cate_column,\n category_embedding_var,\n get_seq_len=True)\n sequence_lengths = [\n his_item_sequence_length, his_category_sequence_length\n ]\n his_item_emb = tf.concat([his_item_embedding, his_category_embedding],\n 2)\n sequence_length = _assert_all_equal_and_return(sequence_lengths)\n\n # get negative samples item embedding\n noclk_his_item_embedding = self.embedding_input_layer(\n builder, self.noclk_his_item_cate_column, item_embedding_var)\n noclk_his_category_embedding = self.embedding_input_layer(\n builder, self.noclk_his_category_cate_column,\n category_embedding_var)\n\n noclk_his_item_emb = tf.concat(\n [noclk_his_item_embedding, noclk_his_category_embedding], 2)\n\n return uid_emb, item_emb, his_item_emb, noclk_his_item_emb, sequence_length\n\n def top_fc_layer(self, inputs):\n bn1 = tf.layers.batch_normalization(inputs=inputs, name='bn1')\n dnn1 = tf.layers.dense(bn1, 200, activation=None, name='dnn1')\n if args.norelu:\n dnn1 = self.dice(dnn1, name='dice_1')\n else:\n dnn1 = tf.nn.relu(dnn1)\n\n dnn2 = tf.layers.dense(dnn1, 80, activation=None, name='dnn2')\n if args.norelu:\n dnn2 = self.dice(dnn2, name='dice_2')\n else:\n dnn2 = tf.nn.relu(dnn2)\n\n dnn3 = tf.layers.dense(dnn2, 2, activation=None, name='dnn3')\n logits = tf.layers.dense(dnn3, 1, activation=None, name='logits')\n add_layer_summary(dnn1, 'dnn1')\n add_layer_summary(dnn2, 'dnn2')\n add_layer_summary(dnn3, 'dnn3')\n return logits\n\n def prediction(self):\n # input layer to get embedding of features\n with tf.variable_scope('input_layer',\n partitioner=self.input_layer_partitioner,\n reuse=tf.AUTO_REUSE):\n uid_emb, item_emb, his_item_emb, noclk_his_item_emb, sequence_length = self.embedding_input(\n )\n if self.bf16:\n uid_emb = tf.cast(uid_emb, tf.bfloat16)\n item_emb = tf.cast(item_emb, tf.bfloat16)\n his_item_emb = tf.cast(his_item_emb, tf.bfloat16)\n noclk_his_item_emb = tf.cast(noclk_his_item_emb, tf.bfloat16)\n\n item_his_eb_sum = tf.reduce_sum(his_item_emb, 1)\n # mask = tf.sequence_mask(sequence_length, maxlen=MAX_SEQ_LENGTH)\n mask = tf.sequence_mask(sequence_length)\n\n # RNN layer_1\n with tf.variable_scope('rnn_1'):\n run_output_1, _ = tf.nn.dynamic_rnn(\n tf.nn.rnn_cell.GRUCell(self.hidden_size),\n inputs=his_item_emb,\n sequence_length=sequence_length,\n dtype=self.data_tpye,\n scope=\"gru1\")\n tf.summary.histogram('GRU_outputs', run_output_1)\n\n # Aux loss\n aux_loss_scope = tf.variable_scope(\n 'aux_loss', partitioner=self.dense_layer_partitioner)\n with aux_loss_scope.keep_weights(dtype=tf.float32) if self.bf16 \\\n else aux_loss_scope:\n self.aux_loss = self.auxiliary_loss(run_output_1[:, :-1, :],\n his_item_emb[:, 1:, :],\n noclk_his_item_emb[:, 1:, :],\n mask[:, 1:],\n dtype=self.data_tpye,\n stag='gru')\n if self.bf16:\n self.aux_loss = tf.cast(self.aux_loss, tf.float32)\n\n # Attention layer\n attention_scope = tf.variable_scope('attention_layer')\n with attention_scope.keep_weights(dtype=tf.float32) if self.bf16 \\\n else attention_scope:\n _, alphas = self.attention(item_emb,\n run_output_1,\n self.attention_size,\n mask,\n softmax_stag=1,\n stag='1_1',\n mode='LIST',\n return_alphas=True)\n tf.summary.histogram('alpha_outputs', alphas)\n\n # RNN layer_2\n with tf.variable_scope('rnn_2'):\n _, final_state2 = tf.nn.dynamic_rnn(\n VecAttGRUCell(self.hidden_size),\n inputs=[run_output_1, tf.expand_dims(alphas, -1)],\n sequence_length=sequence_length,\n dtype=self.data_tpye,\n scope=\"gru2\")\n tf.summary.histogram('GRU2_Final_State', final_state2)\n\n top_input = tf.concat([\n uid_emb, item_emb, item_his_eb_sum, item_emb * item_his_eb_sum,\n final_state2\n ], 1)\n # Top MLP layer\n top_mlp_scope = tf.variable_scope(\n 'top_mlp_layer',\n partitioner=self.dense_layer_partitioner,\n reuse=tf.AUTO_REUSE,\n )\n with top_mlp_scope.keep_weights(dtype=tf.float32) if self.bf16 \\\n else top_mlp_scope:\n self.logits = self.top_fc_layer(top_input)\n if self.bf16:\n self.logits = tf.cast(self.logits, dtype=tf.float32)\n\n predict = tf.math.sigmoid(self.logits)\n return predict\n\n def optimizer(self):\n self.logits = tf.squeeze(self.logits)\n self.crt_loss = tf.losses.sigmoid_cross_entropy(\n self.label,\n self.logits,\n scope='loss',\n reduction=tf.losses.Reduction.SUM_OVER_BATCH_SIZE)\n loss = self.crt_loss + self.aux_loss\n tf.summary.scalar('sigmoid_cross_entropy', self.crt_loss)\n tf.summary.scalar('aux_loss', self.aux_loss)\n\n tf.summary.scalar('loss', loss)\n\n self.global_step = tf.train.get_or_create_global_step()\n optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate)\n gradients = optimizer.compute_gradients(loss)\n clipped_gradients = [(tf.clip_by_norm(grad, 5), var)\n for grad, var in gradients if grad is not None]\n\n train_op = optimizer.apply_gradients(clipped_gradients,\n global_step=self.global_step)\n\n return train_op, loss\n\n\ndef get_arg_parser():\n parser = argparse.ArgumentParser()\n parser.add_argument('--data_location',\n help='Full path of train data',\n required=False,\n default='./data')\n parser.add_argument('--steps',\n help='set the number of steps on train dataset',\n type=int,\n default=0)\n parser.add_argument('--batch_size',\n help='Batch size to train. Default is 512',\n type=int,\n default=128)\n parser.add_argument('--output_dir',\n help='Full path to logs & model output directory',\n required=False,\n default='./result')\n parser.add_argument('--checkpoint',\n help='Full path to checkpoints input/output directory',\n required=False)\n parser.add_argument('--deep_dropout',\n help='Dropout regularization for deep model',\n type=float,\n default=0.0)\n parser.add_argument('--learning_rate',\n help='Learning rate for model',\n type=float,\n default=0.001)\n parser.add_argument('--save_steps',\n help='set the number of steps on saving checkpoints',\n type=int,\n default=0)\n parser.add_argument('--keep_checkpoint_max',\n help='Maximum number of recent checkpoint to keep',\n type=int,\n default=1)\n parser.add_argument('--bf16',\n help='enable DeepRec BF16 in deep model. Default FP32',\n action='store_true')\n parser.add_argument('--no_eval',\n help='not evaluate trained model by eval dataset.',\n action='store_true')\n parser.add_argument('--timeline',\n help='number of steps on saving timeline. Default 0',\n type=int,\n default=0)\n parser.add_argument(\"--protocol\",\n type=str,\n choices=[\"grpc\", \"grpc++\", \"star_server\"],\n default=\"grpc\")\n parser.add_argument('--inter',\n help='set inter op parallelism threads.',\n type=int,\n default=0)\n parser.add_argument('--intra',\n help='set inter op parallelism threads.',\n type=int,\n default=0)\n parser.add_argument('--input_layer_partitioner',\n help='slice size of input layer partitioner. units MB',\n type=int,\n default=0)\n parser.add_argument('--dense_layer_partitioner',\n help='slice size of dense layer partitioner. units KB',\n type=int,\n default=0)\n parser.add_argument('--norelu', action='store_true')\n return parser\n\n\ndef main(tf_config=None, server=None):\n # check dataset\n print('Checking dataset')\n train_file = args.data_location + '/local_train_splitByUser'\n test_file = args.data_location + '/local_test_splitByUser'\n\n if (not os.path.exists(train_file)) or (not os.path.exists(test_file)) or (\n not os.path.exists(train_file + '_neg')) or (\n not os.path.exists(test_file + '_neg')):\n print(\"Dataset does not exist in the given data_location.\")\n sys.exit()\n\n no_of_training_examples = sum(1 for line in open(train_file))\n no_of_test_examples = sum(1 for line in open(test_file))\n print(\"Numbers of training dataset is {}\".format(no_of_training_examples))\n print(\"Numbers of test dataset is {}\".format(no_of_test_examples))\n\n # set params\n # set batch size & steps\n batch_size = args.batch_size\n if args.steps == 0:\n no_of_epochs = 3\n train_steps = math.ceil(\n (float(no_of_epochs) * no_of_training_examples) / batch_size)\n else:\n no_of_epochs = math.ceil(\n (float(batch_size) * args.steps) / no_of_training_examples)\n train_steps = args.steps\n test_steps = math.ceil(float(no_of_test_examples) / batch_size)\n\n # set fixed random seed\n tf.set_random_seed(2021)\n\n # set directory path\n model_dir = os.path.join(args.output_dir,\n 'model_DIEN_' + str(int(time.time())))\n checkpoint_dir = args.checkpoint if args.checkpoint else model_dir\n print(\"Saving model checkpoints to \" + checkpoint_dir)\n\n # create data pipline\n feature_column = build_feature_cols(args.data_location)\n train_dataset = generate_input_data(train_file, batch_size, no_of_epochs)\n test_dataset = generate_input_data(test_file, batch_size, 1)\n\n iterator = tf.data.Iterator.from_structure(train_dataset.output_types,\n test_dataset.output_shapes)\n next_element = iterator.get_next()\n\n train_init_op = iterator.make_initializer(train_dataset)\n test_init_op = iterator.make_initializer(test_dataset)\n\n # create variable partitioner for distributed training\n num_ps_replicas = len(tf_config['ps_hosts']) if tf_config else 0\n input_layer_partitioner = partitioned_variables.min_max_variable_partitioner(\n max_partitions=num_ps_replicas,\n min_slice_size=args.input_layer_partitioner <<\n 20) if args.input_layer_partitioner else None\n dense_layer_partitioner = partitioned_variables.min_max_variable_partitioner(\n max_partitions=num_ps_replicas,\n min_slice_size=args.dense_layer_partitioner <<\n 10) if args.dense_layer_partitioner else None\n\n # create model\n model = DIEN(feature_column=feature_column,\n learning_rate=args.learning_rate,\n embedding_dim=EMBEDDING_DIM,\n hidden_size=HIDDEN_SIZE,\n attention_size=ATTENTION_SIZE,\n bf16=args.bf16,\n inputs=next_element,\n input_layer_partitioner=input_layer_partitioner,\n dense_layer_partitioner=dense_layer_partitioner)\n\n sess_config = tf.ConfigProto()\n if args.inter:\n sess_config.inter_op_parallelism_threads = args.inter\n if args.intra:\n sess_config.intra_op_parallelism_threads = args.intra\n hooks = []\n\n if tf_config:\n hooks.append(tf.train.StopAtStepHook(last_step=train_steps))\n hooks.append(\n tf.train.LoggingTensorHook(\n {\n 'steps': model.global_step,\n 'loss': model.loss\n },\n every_n_iter=100))\n\n scaffold = tf.train.Scaffold(local_init_op=tf.group(\n tf.global_variables_initializer(),\n tf.local_variables_initializer(),\n tf.tables_initializer(),\n train_init_op))\n\n with tf.train.MonitoredTrainingSession(\n master=server.target,\n is_chief=tf_config['is_chief'],\n checkpoint_dir=checkpoint_dir,\n scaffold=scaffold,\n hooks=hooks,\n # save_checkpoint_steps=args.save_steps,\n log_step_count_steps=100,\n config=sess_config) as sess:\n while not sess.should_stop():\n _, train_loss = sess.run([model.train_op, model.loss])\n else:\n with tf.Session(config=sess_config) as sess:\n sess.run(tf.global_variables_initializer())\n sess.run(tf.local_variables_initializer())\n sess.run(tf.tables_initializer())\n merged = tf.summary.merge_all()\n writer = tf.summary.FileWriter(checkpoint_dir, sess.graph)\n saver = tf.train.Saver(tf.global_variables(),\n max_to_keep=args.keep_checkpoint_max)\n options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\n run_metadata = tf.RunMetadata()\n\n # train model\n sess.run(train_init_op)\n\n start = time.perf_counter()\n for _in in range(0, train_steps):\n if args.save_steps > 0 and (_in % args.save_steps == 0\n or _in == train_steps - 1):\n _, train_loss, events = sess.run(\n [model.train_op, model.loss, merged])\n writer.add_summary(events, _in)\n checkpoint_path = saver.save(sess,\n save_path=os.path.join(\n checkpoint_dir,\n 'DIEN-checkpoint'),\n global_step=_in)\n print(\"Save checkpoint to %s\" % checkpoint_path)\n elif (args.timeline > 0 and _in % args.timeline == 0):\n _, train_loss = sess.run([model.train_op, model.loss],\n options=options,\n run_metadata=run_metadata)\n fetched_timeline = timeline.Timeline(\n run_metadata.step_stats)\n chrome_trace = fetched_timeline.generate_chrome_trace_format(\n )\n print(\"Save timeline to %s\" % checkpoint_dir)\n with open(\n os.path.join(checkpoint_dir,\n 'timeline-%d.json' % _in), 'w') as f:\n f.write(chrome_trace)\n else:\n _, train_loss = sess.run([model.train_op, model.loss])\n\n # print training loss and time cost\n if (_in % 100 == 0 or _in == train_steps - 1):\n end = time.perf_counter()\n cost_time = end - start\n global_step_sec = (100 if _in % 100 == 0 else train_steps -\n 1 % 100) / cost_time\n print(\"global_step/sec: %0.4f\" % global_step_sec)\n print(\"loss = {}, steps = {}, cost time = {:0.2f}s\".format(\n train_loss, _in, cost_time))\n start = time.perf_counter()\n\n # eval model\n if not args.no_eval:\n writer = tf.summary.FileWriter(\n os.path.join(checkpoint_dir, 'eval'))\n\n sess.run(test_init_op)\n sess.run(tf.local_variables_initializer())\n for _in in range(1, test_steps + 1):\n if (_in != test_steps):\n sess.run(\n [model.acc, model.acc_op, model.auc, model.auc_op])\n if (_in % 1000 == 0):\n print(\"Evaluation complate:[{}/{}]\".format(\n _in, test_steps))\n else:\n _, eval_acc, _, eval_auc, events = sess.run([\n model.acc, model.acc_op, model.auc, model.auc_op,\n merged\n ])\n writer.add_summary(events, _in)\n print(\"Evaluation complate:[{}/{}]\".format(\n _in, test_steps))\n print(\"ACC = {}\\nAUC = {}\".format(eval_acc, eval_auc))\n\n\nif __name__ == \"__main__\":\n parser = get_arg_parser()\n args = parser.parse_args()\n\n TF_CONFIG = os.getenv('TF_CONFIG')\n if not TF_CONFIG:\n main()\n else:\n print(TF_CONFIG)\n tf_config = json.loads(TF_CONFIG)\n cluster_config = tf_config.get('cluster')\n ps_hosts = []\n worker_hosts = []\n chief_hosts = []\n for key, value in cluster_config.items():\n if \"ps\" == key:\n ps_hosts = value\n elif \"worker\" == key:\n worker_hosts = value\n elif \"chief\" == key:\n chief_hosts = value\n if chief_hosts:\n worker_hosts = chief_hosts + worker_hosts\n\n if not ps_hosts or not worker_hosts:\n print('TF_CONFIG ERROR')\n sys.exit()\n task_config = tf_config.get('task')\n task_type = task_config.get('type')\n task_index = task_config.get('index') + (1 if task_type == 'worker'\n and chief_hosts else 0)\n\n if task_type == 'chief':\n task_type = 'worker'\n\n is_chief = True if task_index == 0 else False\n cluster = tf.train.ClusterSpec({\n \"ps\": ps_hosts,\n \"worker\": worker_hosts\n })\n server = tf.distribute.Server(cluster,\n job_name=task_type,\n task_index=task_index,\n protocol=args.protocol)\n if task_type == 'ps':\n server.join()\n elif task_type == 'worker':\n with tf.device(\n tf.train.replica_device_setter(\n worker_device=\"/job:worker/task:%d\" % task_index,\n cluster=cluster)):\n main(tf_config={\n 'ps_hosts': ps_hosts,\n 'worker_hosts': worker_hosts,\n 'type': task_type,\n 'index': task_index,\n 'is_chief': is_chief\n },\n server=server)\n else:\n print(\"Task type or index error.\")\n sys.exit()"
] | [
[
"tensorflow.data.TextLineDataset",
"tensorflow.summary.scalar",
"tensorflow.contrib.rnn.python.ops.core_rnn_cell._Linear",
"tensorflow.reshape",
"tensorflow.sparse.slice",
"tensorflow.logging.set_verbosity",
"tensorflow.sigmoid",
"tensorflow.clip_by_norm",
"tensorflow.round",
"tensorflow.variable_scope",
"tensorflow.python.client.timeline.Timeline",
"tensorflow.matmul",
"tensorflow.squeeze",
"tensorflow.math.sigmoid",
"tensorflow.name_scope",
"tensorflow.sequence_mask",
"tensorflow.feature_column.sequence_categorical_column_with_vocabulary_file",
"tensorflow.concat",
"tensorflow.losses.sigmoid_cross_entropy",
"tensorflow.data.Iterator.from_structure",
"tensorflow.feature_column.categorical_column_with_vocabulary_file",
"tensorflow.distribute.Server",
"tensorflow.split",
"tensorflow.identity",
"tensorflow.nn.softmax",
"tensorflow.reduce_sum",
"tensorflow.summary.FileWriter",
"tensorflow.tables_initializer",
"tensorflow.summary.histogram",
"tensorflow.array_ops.transpose",
"tensorflow.train.StopAtStepHook",
"tensorflow.train.LoggingTensorHook",
"tensorflow.python.feature_column.feature_column._LazyBuilder",
"tensorflow.global_variables_initializer",
"tensorflow.train.MonitoredTrainingSession",
"tensorflow.feature_column.input_layer",
"tensorflow.nn.zero_fraction",
"tensorflow.train.get_or_create_global_step",
"tensorflow.data.Dataset.zip",
"tensorflow.nn.safe_embedding_lookup_sparse",
"tensorflow.io.decode_csv",
"tensorflow.constant",
"tensorflow.constant_initializer",
"tensorflow.shape",
"tensorflow.ones_like",
"tensorflow.layers.batch_normalization",
"tensorflow.expand_dims",
"tensorflow.global_variables",
"tensorflow.cast",
"tensorflow.set_random_seed",
"tensorflow.RunOptions",
"tensorflow.Session",
"tensorflow.train.replica_device_setter",
"tensorflow.python.ops.partitioned_variables.min_max_variable_partitioner",
"tensorflow.layers.dense",
"tensorflow.metrics.auc",
"tensorflow.ConfigProto",
"tensorflow.local_variables_initializer",
"tensorflow.control_dependencies",
"tensorflow.nn.sigmoid",
"tensorflow.feature_column.embedding_column",
"tensorflow.nn.rnn_cell.GRUCell",
"tensorflow.summary.merge_all",
"tensorflow.debugging.assert_equal",
"tensorflow.strings.split",
"tensorflow.train.AdamOptimizer",
"tensorflow.reduce_mean",
"tensorflow.train.ClusterSpec",
"tensorflow.sqrt",
"tensorflow.python.feature_column.utils.sequence_length_from_sparse_tensor",
"tensorflow.RunMetadata",
"tensorflow.where",
"tensorflow.square",
"tensorflow.log",
"tensorflow.nn.relu",
"tensorflow.get_variable"
]
] |
aliayub7/CBCL_RGBD | [
"f80c23c5f4521eceef554ae765a06e329dfcd93d"
] | [
"depth_training.py"
] | [
"import numpy as np\nimport sys\nimport os\nimport time\nimport pickle\nfrom PIL import Image\nfrom copy import deepcopy\nimport cv2\nimport json\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.autograd import Variable\nfrom torchvision.utils import save_image\nfrom torchvision import models, datasets\n\nfrom training_functions import train\nfrom training_functions import eval_training\nfrom get_transformed_data import getTransformedData\nfrom img_to_vec import Img2Vec\nimport random\n\nseed=seed = random.randint(0,1000)\nnp.random.seed(seed)\ntorch.manual_seed(seed)\n\nif __name__ == '__main__':\n\n path_to_train = './data/SUN/training_depth'\n path_to_test = './data/SUN/testing_depth'\n total_classes = 19\n\n # hyperparameters\n weight_decay = 5e-4\n classify_lr = 0.01\n classification_epochs = 200\n batch_size = 128\n\n #classify_net\n classify_net = models.vgg16()\n classify_net.classifier[6] = nn.Linear(in_features = 4096, out_features = total_classes)\n classify_net.load_state_dict(torch.load(\"./checkpoint/best_after\"+str(classification_epochs)+\"NYU\"))\n #classify_net.fc = nn.Linear(in_features = 4096, out_features = total_classes)\n\n\n # loss functions\n loss_classify = nn.CrossEntropyLoss()\n\n # SUN Depth\n mean = [0.6983, 0.3918, 0.4474]\n std = [0.1648, 0.1359, 0.1644]\n #NYU Depth\n #mean = [0.4951, 0.3601, 0.4587]\n #std = [0.1474, 0.1950, 0.1646]\n\n # define transforms\n transforms_classification_train = transforms.Compose([\n transforms.Resize(256),\n transforms.RandomCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(mean,std)\n ])\n\n transforms_classification_test = transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean,std)\n ])\n\n\n # classifier training\n train_dataset_classification = datasets.ImageFolder(path_to_train,transforms_classification_train)\n test_dataset_classification = datasets.ImageFolder(path_to_test,transforms_classification_test)\n\n dataloaders_train_classification = torch.utils.data.DataLoader(train_dataset_classification,batch_size = batch_size,\n shuffle=True, num_workers = 4)\n dataloaders_test_classification = torch.utils.data.DataLoader(test_dataset_classification,batch_size = batch_size,\n shuffle=True, num_workers = 4)\n\n optimizer = optim.SGD(classify_net.parameters(),lr=classify_lr,weight_decay=weight_decay,momentum=0.9)\n train_scheduler = optim.lr_scheduler.MultiStepLR(optimizer, [60,120,160], gamma=0.2) #learning rate decay\n classify_net = classify_net.cuda()\n\n epoch_acc = eval_training(classify_net,dataloaders_test_classification,loss_classify,seed)\n\n # now classification phase\n since=time.time()\n for epoch in range(1, classification_epochs):\n train_scheduler.step(epoch)\n classification_loss = train(classify_net,dataloaders_train_classification,optimizer,loss_classify)\n print ('epoch:', epoch, ' classification loss:', classification_loss, ' learning rate:', optimizer.param_groups[0]['lr'])\n epoch_acc = eval_training(classify_net,dataloaders_test_classification,loss_classify,seed)\n print (' ')\n time_elapsed = time.time() - since\n print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))\n torch.save(classify_net.state_dict(), \"./checkpoint/best_after\"+str(classification_epochs)+\"SUNRGBD\")\n"
] | [
[
"torch.utils.data.DataLoader",
"torch.nn.Linear",
"torch.manual_seed",
"numpy.random.seed",
"torch.nn.CrossEntropyLoss",
"torch.optim.lr_scheduler.MultiStepLR"
]
] |
DdeGeus/single-network-panoptic-segmentation | [
"891f13b8bca0f41e298900fe1c73bc3035caef5d"
] | [
"components/anchor_generator.py"
] | [
"import tensorflow as tf\nimport numpy as np\nfrom utils import box_utils\n\ndef generate(base_size,\n stride,\n scales,\n ratios,\n features_height,\n features_width,\n offset=None):\n \"\"\"\n\n Args:\n base_size: (height, width)\n stride: (height, width)\n scales: (height, width)\n ratios: (height, width)\n features_height:\n features_width:\n offset: (height, width)\n\n Returns:\n\n \"\"\"\n\n with tf.variable_scope('anchor_generator'):\n if offset is None:\n offset = [stride[0]/2, stride[1]/2]\n\n features_width = tf.cast(features_width, tf.int32)\n features_height = tf.cast(features_height, tf.int32)\n scales = tf.convert_to_tensor(scales, dtype=tf.float32)\n ratios = tf.convert_to_tensor(ratios, dtype=tf.float32)\n offset = tf.convert_to_tensor(offset, dtype=tf.float32)\n\n scales_grid, ratios_grid = tf.meshgrid(scales,\n ratios)\n\n scales_grid = tf.reshape(scales_grid, [-1, 1])\n ratios_grid = tf.reshape(ratios_grid, [-1, 1])\n\n ratio_sqrts = tf.sqrt(ratios_grid)\n\n heights = scales_grid / ratio_sqrts * base_size[1]\n widths = scales_grid * ratio_sqrts * base_size[0]\n\n x_centers = tf.cast(tf.range(features_width), tf.float32)\n x_centers = x_centers * stride[1]\n y_centers = tf.cast(tf.range(features_height), tf.float32)\n y_centers = y_centers * stride[0]\n # x_centers = x_centers + offset[1]\n # y_centers = y_centers + offset[0]\n\n x_centers, y_centers = tf.meshgrid(x_centers, y_centers)\n\n widths, x_centers = tf.meshgrid(widths, x_centers)\n heights, y_centers = tf.meshgrid(heights, y_centers)\n\n anchor_centers = tf.stack([x_centers, y_centers], axis=2)\n anchor_centers = tf.reshape(anchor_centers, [-1, 2])\n\n anchor_sizes = tf.stack([widths, heights], axis=2)\n anchor_sizes = tf.reshape(anchor_sizes, [-1, 2])\n\n anchors = tf.concat([anchor_centers - .5 * anchor_sizes,\n anchor_centers + .5 * anchor_sizes], 1)\n\n # anchors = box_utils.convert_yxyx_to_xyxy_format(anchors)\n\n return anchors\n\n\nif __name__ == '__main__':\n anchor_size = [128, 128]\n anchor_stride = [8, 8]\n anchor_offset = [0, 0]\n anchor_scales = [0.0625, 0.125, 0.25, 0.5, 1.0, 2.0]\n anchor_ratios = [0.25, 0.5, 1.0, 2.0, 4.0]\n height, width = 64, 128\n anchors = generate(anchor_size,\n anchor_stride,\n anchor_scales,\n anchor_ratios,\n height,\n width)\n\n init = tf.global_variables_initializer()\n with tf.Session(config=tf.ConfigProto(device_count={'GPU': 0})) as sess:\n sess.run(init)\n anchors_out = sess.run(anchors)\n print(anchors_out[-30:])\n print(anchors.shape)\n print(anchors_out[158623])\n\n"
] | [
[
"tensorflow.stack",
"tensorflow.reshape",
"tensorflow.global_variables_initializer",
"tensorflow.meshgrid",
"tensorflow.range",
"tensorflow.sqrt",
"tensorflow.variable_scope",
"tensorflow.cast",
"tensorflow.convert_to_tensor",
"tensorflow.concat",
"tensorflow.ConfigProto"
]
] |
hanranCode/models | [
"9b7fef7bc5df0e0c76f6e579f2efce7752ab8fdf"
] | [
"research/object_detection/builders/post_processing_builder.py"
] | [
"# Copyright 2019 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\n\"\"\"Builder function for post processing operations.\"\"\"\nimport functools\n\nimport tensorflow as tf\nfrom object_detection.builders import calibration_builder\nfrom object_detection.core import post_processing\nfrom object_detection.protos import post_processing_pb2\n\n\ndef build(post_processing_config):\n \"\"\"Builds callables for post-processing operations.\n\n Builds callables for non-max suppression, score conversion, and (optionally)\n calibration based on the configuration.\n\n Non-max suppression callable takes `boxes`, `scores`, and optionally\n `clip_window`, `parallel_iterations` `masks, and `scope` as inputs. It returns\n `nms_boxes`, `nms_scores`, `nms_classes` `nms_masks` and `num_detections`. See\n post_processing.batch_multiclass_non_max_suppression for the type and shape\n of these tensors.\n\n Score converter callable should be called with `input` tensor. The callable\n returns the output from one of 3 tf operations based on the configuration -\n tf.identity, tf.sigmoid or tf.nn.softmax. If a calibration config is provided,\n score_converter also applies calibration transformations, as defined in\n calibration_builder.py. See tensorflow documentation for argument and return\n value descriptions.\n\n Args:\n post_processing_config: post_processing.proto object containing the\n parameters for the post-processing operations.\n\n Returns:\n non_max_suppressor_fn: Callable for non-max suppression.\n score_converter_fn: Callable for score conversion.\n\n Raises:\n ValueError: if the post_processing_config is of incorrect type.\n \"\"\"\n if not isinstance(post_processing_config, post_processing_pb2.PostProcessing):\n raise ValueError('post_processing_config not of type '\n 'post_processing_pb2.Postprocessing.')\n non_max_suppressor_fn = _build_non_max_suppressor(\n post_processing_config.batch_non_max_suppression)\n score_converter_fn = _build_score_converter(\n post_processing_config.score_converter,\n post_processing_config.logit_scale)\n if post_processing_config.HasField('calibration_config'):\n score_converter_fn = _build_calibrated_score_converter(\n score_converter_fn,\n post_processing_config.calibration_config)\n return non_max_suppressor_fn, score_converter_fn\n\n\ndef _build_non_max_suppressor(nms_config):\n \"\"\"Builds non-max suppresson based on the nms config.\n\n Args:\n nms_config: post_processing_pb2.PostProcessing.BatchNonMaxSuppression proto.\n\n Returns:\n non_max_suppressor_fn: Callable non-max suppressor.\n\n Raises:\n ValueError: On incorrect iou_threshold or on incompatible values of\n max_total_detections and max_detections_per_class.\n \"\"\"\n if nms_config.iou_threshold < 0 or nms_config.iou_threshold > 1.0:\n raise ValueError('iou_threshold not in [0, 1.0].')\n if nms_config.max_detections_per_class > nms_config.max_total_detections:\n raise ValueError('max_detections_per_class should be no greater than '\n 'max_total_detections.')\n non_max_suppressor_fn = functools.partial(\n post_processing.batch_multiclass_non_max_suppression,\n score_thresh=nms_config.score_threshold,\n iou_thresh=nms_config.iou_threshold,\n max_size_per_class=nms_config.max_detections_per_class,\n max_total_size=nms_config.max_total_detections,\n use_static_shapes=nms_config.use_static_shapes,\n use_class_agnostic_nms=nms_config.use_class_agnostic_nms,\n max_classes_per_detection=nms_config.max_classes_per_detection)\n return non_max_suppressor_fn\n\n\ndef _score_converter_fn_with_logit_scale(tf_score_converter_fn, logit_scale):\n \"\"\"Create a function to scale logits then apply a Tensorflow function.\"\"\"\n def score_converter_fn(logits):\n scaled_logits = tf.divide(logits, logit_scale, name='scale_logits')\n return tf_score_converter_fn(scaled_logits, name='convert_scores')\n score_converter_fn.__name__ = '%s_with_logit_scale' % (\n tf_score_converter_fn.__name__)\n return score_converter_fn\n\n\ndef _build_score_converter(score_converter_config, logit_scale):\n \"\"\"Builds score converter based on the config.\n\n Builds one of [tf.identity, tf.sigmoid, tf.softmax] score converters based on\n the config.\n\n Args:\n score_converter_config: post_processing_pb2.PostProcessing.score_converter.\n logit_scale: temperature to use for SOFTMAX score_converter.\n\n Returns:\n Callable score converter op.\n\n Raises:\n ValueError: On unknown score converter.\n \"\"\"\n if score_converter_config == post_processing_pb2.PostProcessing.IDENTITY:\n return _score_converter_fn_with_logit_scale(tf.identity, logit_scale)\n if score_converter_config == post_processing_pb2.PostProcessing.SIGMOID:\n return _score_converter_fn_with_logit_scale(tf.sigmoid, logit_scale)\n if score_converter_config == post_processing_pb2.PostProcessing.SOFTMAX:\n return _score_converter_fn_with_logit_scale(tf.nn.softmax, logit_scale)\n raise ValueError('Unknown score converter.')\n\n\ndef _build_calibrated_score_converter(score_converter_fn, calibration_config):\n \"\"\"Wraps a score_converter_fn, adding a calibration step.\n\n Builds a score converter function witha calibration transformation according\n to calibration_builder.py. Calibration applies positive monotonic\n transformations to inputs (i.e. score ordering is strictly preserved or\n adjacent scores are mapped to the same score). When calibration is\n class-agnostic, the highest-scoring class remains unchanged, unless two\n adjacent scores are mapped to the same value and one class arbitrarily\n selected to break the tie. In per-class calibration, it's possible (though\n rare in practice) that the highest-scoring class will change, since positive\n monotonicity is only required to hold within each class.\n\n Args:\n score_converter_fn: callable that takes logit scores as input.\n calibration_config: post_processing_pb2.PostProcessing.calibration_config.\n\n Returns:\n Callable calibrated score coverter op.\n \"\"\"\n calibration_fn = calibration_builder.build(calibration_config)\n def calibrated_score_converter_fn(logits):\n converted_logits = score_converter_fn(logits)\n return calibration_fn(converted_logits)\n calibrated_score_converter_fn.__name__ = (\n 'calibrate_with_%s' % calibration_config.WhichOneof('calibrator'))\n return calibrated_score_converter_fn\n"
] | [
[
"tensorflow.divide"
]
] |
Aditibansal2603/fake-news-predictor | [
"9d4ba2ed95799ca63d0fa7f3f5ad0e6f09b9b215"
] | [
"app.py"
] | [
"import re\nimport pickle\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom string import punctuation\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.tokenize import sent_tokenize, word_tokenize \nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom flask import Flask, render_template, request, jsonify\n\n# import MLP module definition\nfrom models import MLP\n\nclass CustomUnpickler(pickle.Unpickler):\n\n def find_class(self, module, name):\n try:\n return super().find_class(__name__, name)\n except AttributeError:\n return super().find_class(module, name)\n\n# load saved model parameters and vectorizers\nmodel = CustomUnpickler(open('data/multi-layer-perceptron-parameters.pkl', 'rb')).load()\ntext_vectorizer = CustomUnpickler(open('data/text_vectorizer.pkl','rb')).load()\n\n\ndef preprocess(df):\n \"\"\"\n Preprocess user input in the same way we preprocessed the training data.\n\n 1. Remove non-alphabetic characters, convert to lowercase\n 2. Tokenize (word_tokenizer from nltk)\n 3. Lemmatize (WordNetLemmatizer)\n 4. Vectorize (CountVectorizer)\n\n Use the same CountVectorizers from training in order to extract\n the same features and have the same output dimensions.\n \"\"\"\n lemmatizer = WordNetLemmatizer()\n\n text_processed = []\n for text in df.text:\n # remove punctuation and lowercase\n text = re.sub(r'[^a-zA-Z]', ' ', text) \n text = text.lower()\n \n # tokenize and lemmatize tokens\n tokens = word_tokenize(text)\n tokens = [lemmatizer.lemmatize(x) for x in tokens]\n text_processed.append(' '.join(tokens))\n\n # vectorize\n text_matrix = text_vectorizer.transform(text_processed).toarray()\n \n # return np matrix\n return text_matrix\n\napp = Flask(__name__)\n\[email protected]('/')\ndef home():\n return render_template('home.html')\n\[email protected]('/predict', methods=['POST'])\ndef predict():\n text = request.json['text']\n d = {'text': [text]}\n # create dataframe from user input\n X_df = pd.DataFrame(data=d)\n\n # preprocess df and return np array\n X_np = preprocess(X_df)\n\n # convert to tensor\n X_tensor = torch.Tensor(X_np)\n\n # predict\n y_pred = model(X_tensor)\n y_pred_max = torch.max(y_pred,1)[1]\n if y_pred_max == 1:\n result = \"real\"\n else:\n result = \"fake\"\n return jsonify({\"result\": result})\n\nif __name__ == '__main__':\n app.run()"
] | [
[
"pandas.DataFrame",
"torch.Tensor",
"torch.max"
]
] |
maciek3000/GnuCash-Expenses-Vis | [
"ab0849f49b9b50f81798fc4c769b0aee6ae03b1e"
] | [
"flask_app/bkapp/bk_settings.py"
] | [
"import pandas as pd\nfrom datetime import datetime\n\nfrom bokeh.models.widgets import RadioGroup, CheckboxGroup, DateRangeSlider\nfrom bokeh.layouts import column\n\nfrom ..observer import Observer\nfrom .pandas_functions import create_combinations_of_sep_values\n\n\nclass Settings(object):\n \"\"\"Settings Object used in BokehApp, providing means for the User to manipulate range of data\n in other Views in flask_app.\n\n Object expects:\n - 3 Series with Column data from Expense Dataframe:\n - .category Column\n - .all Column\n - .date Column\n - Category Sep String which defines how Elements in .all categories should be split\n - category_types labels defining what will be shown as Radio Buttons for Category Type\n - Observer instance which will be observing some attributes\n - bkapp parent attribute, which will be notified by observer on change of few attributes.\n\n Main methods are:\n - category_options that returns gridplot to manipulate Categories in the dataframe\n - month_range_options that returns gridplot to manipulate Months in the dataframe\n - initialize_settings_variables to initialize Object variables.\n\n\n Settings Object defines 3 watched properties:\n - chosen_categories\n - chosen_category_type\n - chosen_months\n Upon change on any of those properties, observer instance notifies parent \"bkapp\" object.\n\n Attributes of the instance Object are described as single-line comments in __init__() method;\n\n\n \"\"\"\n\n # TODO: synchronize chosen months and categories - it might happen that there is no such category\n # TODO: in chosen Month Range\n\n chosen_categories = Observer.watched_property(\"observer\", \"chosen_categories\", \"parent\")\n chosen_category_type = Observer.watched_property(\"observer\", \"chosen_category_type\", \"parent\")\n chosen_months = Observer.watched_property(\"observer\", \"chosen_months\", \"parent\")\n\n def __init__(self, simple_categories_series, extended_categories_series, date_series,\n category_sep, category_types, observer, bkapp):\n\n # Observer Variables\n self.parent = bkapp\n self.observer = observer\n\n # Original Data\n self.original_simple_categories = simple_categories_series\n self.original_extended_categories = extended_categories_series\n self.original_dates = date_series\n\n # Initialization Variables\n self.category_sep = category_sep\n self.category_type_labels = category_types\n\n # Category State Variables\n self.all_categories_simple = None\n self.all_categories_extended = None\n self.all_categories_combinations = None\n self.all_categories = None\n\n # Elements\n self.checkbox_group = None\n\n # Month Range Variables\n self.all_months = None\n\n # Initialization State\n self.are_categories_initialized = False\n self.is_month_range_initialized = False\n\n def category_options(self):\n \"\"\"Returns gridplot (bokeh layout or Element) defining elements for the User to manipulate Data shown in\n other views.\n\n Function first checks if the category variables are initialized and if not, initializes them. Then two\n bokeh widgets are created: Radio Group and Checbox Group and both are put into the column layout.\n\n Category Type Radio Group allows to choose which category column will be used in dataframes (either\n .category or .all) and if the categories will be extracted as they are (either in \"simple\" or \"extended\"\n options) or if the \"combinations\" of categories will be created for User's choosing\n (e.g. Expenses:Family:Grocery:Fruits will provide 4 different categories:\n - \"Expenses\"\n - \"Expenses:Family\"\n - \"Expenses:Family:Grocery\"\n - \"Expenses:Family:Grocery:Fruits\".\n\n Checkbox Group will then provide all choosable categories (from chosen category type) for the User\n to check and uncheck and therefore filter/unfilter them from the dataframes.\n\n Elements on creation take data from respective instance attributes - this way navigating between\n different views and then coming back to Settings view will \"remember\" previous choice of the User.\n\n Callbacks are defined for each Element so that it will be responsive to User choosing.\n\n Additionally, Checkbox Group is set into .checkbox_group attribute so that change in Category Type\n can also trigger change in Checkbox Group.\n\n Returns column layout.\n \"\"\"\n\n if self.are_categories_initialized is False:\n self.__initialize_categories()\n\n chosen_index = self.chosen_category_type\n\n category_type_chooser = RadioGroup(\n labels=self.category_type_labels, active=chosen_index,\n css_classes=[\"category_types_buttons\"], inline=True\n )\n\n checkbox_group = CheckboxGroup(\n labels=self.all_categories,\n active=[self.all_categories.index(x) for x in self.chosen_categories],\n css_classes=[\"category_checkbox\"]\n )\n\n # set as attribute for RadioGroup Buttons Updates to have access to it\n self.checkbox_group = checkbox_group\n\n # Callbacks\n def callback_on_category_type_change(attr, old, new):\n if new != old:\n self.__update_categories_on_category_type_change(new)\n\n category_type_chooser.on_change(\"active\", callback_on_category_type_change)\n\n def callback_on_checkbox_change(new):\n self.__update_chosen_categories_on_new(new)\n\n checkbox_group.on_click(callback_on_checkbox_change)\n\n # Grid\n grid = column(\n category_type_chooser,\n checkbox_group\n )\n\n return grid\n\n def month_range_options(self):\n \"\"\"Returns gridplot (bokeh layout or Element) defining elements for the User to manipulate Data shown in\n other views.\n\n Function first checks if the months variables are initialized and if not, initializes them. Then one\n bokeh widget - DateRangeSlider is created.\n\n DateRangeSlider will allow User to filter data to Months between two \"borders\" of the Slider. Even though\n DateRangeSlider defines step: 1 (so all days from the months are shown), formatter applied will only show\n month-year values (\"%b-%Y).\n Additionally, defined callback checks months of start-stop values and compares them to months from\n old values. This way, callbacks aren't triggered for every slight change in the Slider and change in\n .chosen_months is only triggered when the actual change in months happens.\n\n Values for the Slider are also taken from instance attributes - this way User's previous choice is\n remembered and can be shown upon coming back to Settings View.\n\n Returns DateRangeSlider.\n \"\"\"\n\n if self.is_month_range_initialized is False:\n self.__initialize_months()\n\n sld = DateRangeSlider(start=self.all_months[0], end=self.all_months[-1], step=1,\n value=(self.chosen_months[0], self.chosen_months[-1]),\n format=\"%b-%Y\", title=\"Chosen Month Range: \",\n css_classes=[\"month_range_slider\"])\n\n def month_range_callback(attr, old, new):\n formatting = \"%Y-%m\"\n old_str = self.__create_timetuple_string_from_timestamp(old, formatting)\n new_str = self.__create_timetuple_string_from_timestamp(new, formatting)\n if old_str != new_str:\n self.__update_chosen_months(new)\n\n sld.on_change(\"value\", month_range_callback)\n\n return sld\n\n def initialize_settings_variables(self):\n \"\"\"Helper function for calling initialization different variables.\"\"\"\n self.__initialize_categories()\n self.__initialize_months()\n\n def __initialize_categories(self):\n \"\"\"Initializes variables for the Category Gridplot.\n\n Initialized instance attributes are:\n - .all_categories_simple - list of \"simple\" categories (taken from .category column)\n - .all_categories_extended - list of \"extended\" categories (taken from .all column)\n - .all_categories_combinations - list of \"combinations\" from .all column (see category_options() docs)\n\n Those attributes will be used as runtime containers for different categories values, from which\n User's choices will be extracted and loaded into .all_categories and .chosen_categories attributes.\n .all_categories and .chosen_categories are used as attributes for determining what is the User's choice.\n\n Additionally, .chosen_category_type is set to default 0 (\"simple\") and so are .all_categories and\n .chosen_categories attributes.\n\n .are_categories_initialized flag is set to True as a way to show that Category Variables are initialized.\n \"\"\"\n simple = self.original_simple_categories.sort_values().unique().tolist()\n extended = self.original_extended_categories.sort_values().unique().tolist()\n combinations = create_combinations_of_sep_values(extended, self.category_sep)\n\n self.all_categories_simple = simple\n self.all_categories_extended = extended\n self.all_categories_combinations = combinations\n\n self.chosen_category_type = 0\n self.all_categories = simple\n self.chosen_categories = simple\n\n self.are_categories_initialized = True\n\n def __initialize_months(self):\n \"\"\"Initializes variables for the Month Gridplot.\n\n Initialized instance attributes are:\n - .all_months containing data of different months present in .date column\n - .chosen_months containing month range chosen by the User.\n\n .all_months attribute is created as a \"MS\" (MonthStart) pd.date_range between the first\n and the last date present in .original_dates Series (.date column from dataframe).\n\n Both .all_months and .chosen_months are used as variables for the DateRangeSlider to extract all months\n present in the dataframe and User's choice of filtering, respectively.\n\n .are_categories_initialized flag is set to True as a way to show that Category Variables are initialized.\n \"\"\"\n start_date = self.original_dates.min()\n stop_date = self.original_dates.max()\n\n all_dates_range = pd.to_datetime(pd.date_range(start_date, stop_date, freq=\"MS\")).tolist()\n\n self.all_months = all_dates_range\n self.chosen_months = all_dates_range\n\n self.is_month_range_initialized = True\n\n def __update_categories_on_category_type_change(self, index):\n \"\"\"Callback used on a change to Category Type Radio Button.\n\n Index argument requires integer in range [0, 2]. This determines which category type was chosen and what\n data should be loaded into .all_categories and .chosen_categories variables.\n\n Index options are (hardcoded):\n - 0: simple categories\n - 1: extended categories\n - 2: combination categories\n\n Additionally to .all_categories and .chosen_categories variables, .chosen_category_type is also set to\n chosen index (as a way to preserve state).\n\n As change in Category Type should also propagate change to Category Checkbox, .checkbox_group Widget is\n updated with new categories:\n - .labels attribute with all possible Categories\n - .active attribute with list of Integers from 0 to len(New Categories).\n \"\"\"\n\n if index == 0:\n new = self.all_categories_simple\n elif index == 1:\n new = self.all_categories_extended\n elif index == 2:\n new = self.all_categories_combinations\n else:\n raise Exception(\"How did I get here?\")\n\n self.all_categories = new\n self.chosen_categories = new\n\n self.chosen_category_type = index\n\n self.checkbox_group.labels = new\n self.checkbox_group.active = list(range(len(new)))\n\n def __update_chosen_categories_on_new(self, new):\n \"\"\"Updates .chosen_categories variable based on new attribute - list of indices.\n\n Function updates .chosen_categories with Categories (Strings) taken from .all_categories, based on\n indices provided in new attribute.\n\n .chosen_categories attribute is updated.\n \"\"\"\n self.chosen_categories = [self.all_categories[x] for x in new]\n\n def __create_timetuple_string_from_timestamp(self, single_tuple, date_format):\n \"\"\"Creates 2 Element Tuples of Strings formatted to date_format from 2 Element Tuples of Timestamps.\n\n Function accepts single_tuple tuple of Timestamp variables. As those Timestamps come from\n DateRangeSlider, they need to be divided by 1000 (1e3) for datetime.fromtimestamp to work.\n Datetime elements are then converted into Strings of date_format and returned.\n\n Additionally, if type of elements in the single_tuple is pd.Timestamp, values are first converted into\n timestamps and then multiplied by 1000 for the rest of the function to work. This is needed for\n the DateRangeSlider to work, as initially values are extracted might be pd.Timestamps.\n\n Returns 2 Element Tuple of Strings from Dates (with date_format).\n \"\"\"\n\n # TODO: check if Timestamps are actually loaded\n # checking for Timestamp as they might be in Slider Values initially (before User interaction)\n if (type(single_tuple[0]) is pd.Timestamp) and (type(single_tuple[1]) is pd.Timestamp):\n single_tuple = tuple([x.timestamp() * 1e3 for x in single_tuple])\n\n # divided by 1000 (1e3) as DateRangeSlider provides timestamp multiplied by thousand\n val = tuple(map(lambda x: datetime.fromtimestamp(float(x) / 1e3).strftime(date_format), single_tuple))\n return val\n\n def __update_chosen_months(self, new):\n \"\"\"Function updates .chosen_months attribute with date_range based on new tuples values.\n\n new tuple included two Timestamps from the DateRangeSlider - beginning and the end of the Date Range\n chosen by the User.\n Values from the tuple are first changed into datetime (divided by 1000 as they come from DateRangeSlider)\n and then their day is replaced to 1 (to avoid problems with missing months when date_range is created).\n Strings in format \"%Y-%m-%d are created and then are inserted into pd.date_range which creates new\n range of dates with frequency \"MS\" (Month Start). Such DateRange is then loaded into .chosen_months\n attribute.\n\n .chosen_months attribute is updated.\n \"\"\"\n # done to first convert timestamp to datetime and then to set datetime to day 1 - this way\n # date_range is properly created\n new = tuple(map(lambda x: datetime.fromtimestamp(float(x) / 1e3), new))\n\n # TODO: check if converting to String is necessary\n new = [datetime(year=x.year, month=x.month, day=1).strftime(\"%Y-%m-%d\") for x in new]\n dr = pd.date_range(new[0], new[1], freq=\"MS\", normalize=True).tolist()\n\n self.chosen_months = dr\n"
] | [
[
"pandas.date_range"
]
] |
mikgroup/subtle_data_crimes | [
"210025d9cb8f92583f5f983be15af06b57cfea36"
] | [
"subtle_data_crimes/functions/zpad_funcs.py"
] | [
"\"\"\"\nThis module includes functions for experiments with the zero-padding preprocessing pipeline (subtle inverse crime I).\n\nEfrat Shimron (UC Berkeley, 2021).\n\"\"\"\n\nimport numpy as np\nfrom subtle_data_crimes.functions.utils import merge_multicoil_data, calc_pad_half\n\n################################## helper func #########################################################\ndef zpad_merge_scale(ksp_block_multicoil, pad_ratio):\n ''' inputs:\n kspace - numpy array of size [Ncoils, NX, NY]\n pad_ratio - numpy array (scalar) that denotes the desired padding ratio\n '''\n\n NX = ksp_block_multicoil.shape[1]\n NY = ksp_block_multicoil.shape[2]\n\n\n ############## zero-pad, merge & save ###################\n\n pad_half_dim1, N_tot_dim1 = calc_pad_half(NX, pad_ratio)\n pad_half_dim2, N_tot_dim2 = calc_pad_half(NY, pad_ratio)\n\n padding_lengths = ((0, 0), (pad_half_dim1, pad_half_dim1), (pad_half_dim2, pad_half_dim2))\n\n\n ksp_block_multicoil_padded = np.pad(ksp_block_multicoil, padding_lengths, mode='constant',\n constant_values=(0, 0))\n\n # compute a single *magnitude* image from the data\n im_mag = merge_multicoil_data(ksp_block_multicoil_padded)\n\n # normalization\n magnitude_vals = im_mag.reshape(-1)\n mag_vals_sorted = np.sort(magnitude_vals)\n k = int(round(0.98 * magnitude_vals.shape[0]))\n scale_factor = mag_vals_sorted[k]\n im_mag_scaled = im_mag / scale_factor\n\n return im_mag_scaled"
] | [
[
"numpy.sort",
"numpy.pad"
]
] |
SVAI/teamSTIR | [
"9f59f6e655a86bad4f917eb64ebd066401efc428"
] | [
"nf_dataset.py"
] | [
"# by @eickenberg\n\nimport torch\nimport numpy as np\n\nfrom patch_dataset import PatchDataset\nfrom torch.utils.data import ConcatDataset\n\nimport glob\nimport os\nimport nibabel\n\nclass ZipDataset(torch.utils.data.Dataset):\n\n def __init__(self, *datasets):\n self.datasets = datasets\n\n def __len__(self):\n return min(len(dataset) for dataset in self.datasets)\n\n def __getitem__(self, i):\n return tuple(dataset[i] for dataset in self.datasets)\n\n\n\nclass NFDataset(torch.utils.data.Dataset):\n\n def __init__(self, keys=(), exclude_subjects=(),\n data_transform=None,\n target_transform=None):\n self.keys = keys\n self.exclude_subjects = exclude_subjects\n self.data_transform = data_transform\n self.target_transform = target_transform\n self.data_transform = data_transform\n\n self.build()\n\n def build(self):\n subject_folders = sorted(glob.glob(os.path.join(self.nf_folder, \"WBMRI*\")))\n for ex in self.exclude_subjects:\n for i, s in enumerate(subject_folders):\n if ex in s:\n del subject_folders[i]\n self.subject_folders = subject_folders\n\n self.stir_patch_datasets = []\n self.annotation_patch_datasets = []\n \n self.count64_lengths = []\n self.positive_counts = []\n self.random_negative_counts = []\n \n counter = 0\n self.distrib = np.zeros(3000, dtype=int)\n\n for subject_folder in subject_folders:\n stir_file = os.path.join(subject_folder, \"STIR_file.nii\")\n stir_vol = nibabel.load(stir_file).get_data()\n stir_vol[stir_vol >= 3000] = 0\n self.distrib += np.bincount(stir_vol.ravel(), minlength=3000)\n self.stir_patch_datasets.append(\n PatchDataset(stir_vol[:, ::-1].astype('float32'), \n transform=self.data_transform))\n # ^note the axis flip\n\n annotation_file = os.path.join(subject_folder, \"annotation_file.nii.gz\")\n annotation_vol = (nibabel.load(annotation_file).get_data() > 0).astype('bool') # <- note the axis flip\n self.annotation_patch_datasets.append(\n PatchDataset(annotation_vol,\n transform=self.target_transform))\n\n count64_file = os.path.join(subject_folder, \"count64_file.nii.gz\")\n count64_vol = nibabel.load(count64_file)\n count64_data = count64_vol.get_data()\n self.count64_lengths.append(count64_data.size)\n\n positive_counts = np.where(count64_data.ravel() > 0)[0]\n negative_counts = np.random.choice(np.where(count64_data.ravel() == 0)[0],\n len(positive_counts), replace=False)\n self.positive_counts.append(positive_counts + counter)\n self.random_negative_counts.append(negative_counts + counter)\n counter += self.count64_lengths[-1]\n\n self.positive_counts = np.concatenate(self.positive_counts)\n self.random_negative_counts = np.concatenate(self.random_negative_counts)\n\n self.subset_indices = np.stack((self.positive_counts, self.random_negative_counts),\n axis=1).ravel()\n\n\n self.stir_patches = ConcatDataset(self.stir_patch_datasets)\n self.annotation_patches = ConcatDataset(self.annotation_patch_datasets)\n\n self.dataset = ZipDataset(self.stir_patches, self.annotation_patches)\n\n def __getitem__(self, i):\n return self.dataset[i]\n\n def __len__(self):\n return len(self.dataset)\n\n\n\n\n\nif __name__ == \"__main__\":\n\n from torchvision.transforms import Compose, Normalize, ToTensor\n\n data_transform = Compose([ ToTensor(),\n Normalize([0.], [300.]),\n Normalize([.5], [.5]),\n ])\n\n #target_transform = ToTensor()\n nfdataset = NFDataset(\"/home/michael/nf_dataset\",\n data_transform=data_transform,\n target_transform=target_transform)\n\n sampler = torch.utils.data.sampler.SubsetRandomSampler(\n nfdataset.positive_counts)\n\n dataloader = torch.utils.data.DataLoader(\n nfdataset, sampler=sampler, batch_size=32)\n"
] | [
[
"torch.utils.data.DataLoader",
"numpy.zeros",
"torch.utils.data.ConcatDataset",
"torch.utils.data.sampler.SubsetRandomSampler",
"numpy.stack",
"numpy.concatenate"
]
] |
ireneferfo/VanGoghColorz | [
"e41bd6a08cef6b2954c0e60613dd9ddd0fbc7045"
] | [
"get_colors.py"
] | [
"from collections import Counter\nfrom sklearn.cluster import KMeans\nimport cv2\n\nsizeX = 600\nsizeY = 400\n\ndef preprocess(raw):\n image = cv2.resize(raw, (sizeX, sizeY), interpolation = cv2.INTER_AREA) \n image = image.reshape(image.shape[0]*image.shape[1], 3)\n return image\n\n \ndef rgb_to_hex(rgb_color):\n hex_color = \"#\"\n for i in rgb_color:\n hex_color += (\"{:02x}\".format(int(i)))\n return hex_color\n\n\ndef analyze(img, n_colors):\n clf = KMeans(n_clusters = n_colors, random_state = 0)\n color_labels = clf.fit_predict(img)\n center_colors = clf.cluster_centers_ # in RGB\n\n counts = Counter(color_labels)\n ordered_colors = [rgb_to_hex(center_colors[i]) for i in counts.keys()]\n\n d = {}\n for i in range(len(ordered_colors)):\n d[ordered_colors[i]] = list(counts.values())[i]/(sizeX*sizeY)\n d = {k: v for k, v in sorted(d.items(), key=lambda item: item[1], reverse = True)}\n\n return d\n\n\ndef extract_colors(image_path, n_colors = 10):\n image = cv2.imread(image_path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n modified_image = preprocess(image)\n return analyze(modified_image, n_colors)"
] | [
[
"sklearn.cluster.KMeans"
]
] |
DaJansenGit/TEASER | [
"25edb5be547a750e3ad35c02a97949d2b45bce32"
] | [
"teaser/examples/e9_building_data_import_from_excel.py"
] | [
"# -*- coding: utf-8 -*-\n# @Author: Martin Raetz\n# @Date: 2019-02-19 18:41:56\n# @Last Modified by: Martin Rätz\n# @Last Modified time: 29.11.2019\n\n\"\"\"\nThis script demonstrates how a building can be generated by importing building\ndata from excel.\nAn appropriate example file with some building data is imported from\nexamplefiles/ExcelBuildingData_Sample.xlsx.\n\nIn the excel every room is listed by its own, via a custom defined zoning\nalgorithm these rooms are combined to zones.\nThe user needs to adjust the zoning to his needs.\nSee # Block: Zoning methodologies (define your zoning function here)\n\nLimitations and assumptions:\n- Outer and inner wall area depend on the calculations done in the excel\n- Ground floor area is only as big the respective net area of the heated room\nvolume (NetArea)\n- Floor area is only as big the respective net area of the heated room volume\n(NetArea)\n- Rooftop area is only as big the respective net area of the heated room\nvolume (NetArea)\n- Rooftops are flat and not tilted, see \"RooftopTilt\"\n- Ceiling area is only as big the respective net area of the heated room\nvolume (NetArea)\n- Ceiling, floor and inner walls are only respected by half their area,\nsince they belong half to the respective\nand half to the adjacent zone\n- Orientations are clockwise in degree, 0° is directed north\n\n-respective construction types have to be added to the TypeBuildingElements.json\n-respective UsageTypes for Zones have to be added to the UseConditions.json\n-excel file format has to be as shown in the \"ExcelBuildingData_Sample.xlsx\"\n\nInformation about the required excel format:\n#Documentation in progress!\n-yellowed columns are necessary input to teaser -> don´t change column\nheader, keep value names consistent.\n-non yellowed columns may either not be used or be used for your zoning\nalgorithm\n-Under the cell ‚Usage type‘ you will see some cells that are blank but have\ntheir row filled.\nIt means the blank cell actually belongs to the Usage type above but in that\nspecific row we filled the characteristics\nof the window/wall of a different orientation of the same exact room. That\nmeans every row is either a new room or a\nnew orientation of that room. A room might have two outer walls in two\ndifferent orientation so for each outer wall,\na an extra row defining the respective orientation is added\n-The entries in the excel sheet must be consistent for python being able to\nconvert it.\n-If an inner wall is reaching inside a room but is not the limit of the room,\nit should be accounted with 2x the area\n\"\"\"\n\nimport os\nfrom teaser.project import Project\nfrom teaser.logic.buildingobjects.building import Building\nfrom teaser.logic.buildingobjects.thermalzone import ThermalZone\nfrom teaser.logic.buildingobjects.useconditions import UseConditions\nfrom teaser.logic.buildingobjects.buildingphysics.outerwall import OuterWall\nfrom teaser.logic.buildingobjects.buildingphysics.floor import Floor\nfrom teaser.logic.buildingobjects.buildingphysics.rooftop import Rooftop\nfrom teaser.logic.buildingobjects.buildingphysics.groundfloor import GroundFloor\nfrom teaser.logic.buildingobjects.buildingphysics.ceiling import Ceiling\nfrom teaser.logic.buildingobjects.buildingphysics.window import Window\nfrom teaser.logic.buildingobjects.buildingphysics.innerwall import InnerWall\nimport pandas as pd\nimport numpy as np\nimport warnings\nimport shutil\n\n\ndef import_data(path=None, sheet_names=None):\n \"\"\"\n Import data from the building data excel file and perform some\n preprocessing for nan and empty cells.\n If several sheets are imported, the data is concatenated to one dataframe\n\n Parameters\n ----------\n path: str\n path to the excel file that should be imported\n sheet_names: list or str\n sheets of excel that should be imported\n \"\"\"\n\n # process an import of a single sheet as well as several sheets,\n # which will be concatenated with an continuous index\n if type(sheet_names) == list:\n data = pd.DataFrame()\n _data = pd.read_excel(io=path, sheet_name=sheet_names, header=0, index_col=None)\n for sheet in sheet_names:\n data = data.append(_data[sheet], sort=False)\n data = data.reset_index(drop=False)\n data[\"index\"] = data[\"index\"] + 2 # sync the index with the excel index\n else:\n data = pd.read_excel(io=path, sheet_name=sheet_names, header=0, index_col=0)\n\n # Cut of leading or tailing white spaces from any string in the dataframe\n data = data.applymap(lambda x: x.strip() if type(x) is str else x)\n\n # Convert every N/A, nan, empty strings and strings called N/a, n/A, NAN,\n # nan, na, Na, nA or NA to np.nan\n data = data.replace(\n [\"\", \"N/a\", \"n/A\", \"NAN\", \"nan\", \"na\", \"Na\", \"nA\", \"NA\"], np.nan, regex=True\n )\n data = data.fillna(np.nan)\n\n return data\n\n\ndef get_list_of_present_entries(list_):\n \"\"\"\n Extracts a list of all in the list available entries, discarding \"None\"\n and \"nan\" entries\n\n Parameters\n ----------\n list_: list\n list that shall be processed\n \"\"\"\n\n _List = []\n for x in list_:\n if x not in _List:\n if not None:\n if not pd.isna(x):\n _List.append(x)\n return _List\n\n\n# Block: Zoning methodologies (define your zoning function here)\n# -------------------------------------------------------------\ndef zoning_example(data):\n \"\"\"\n This is an example on how the rooms of a building could be aggregated to\n zones.\n\n In this example the UsageType has to be empty in the case that the\n respective line does not represent another\n room but a different orientated wall or window belonging to a room that\n is already declared once in the excel file.\n\n Parameters\n ----------\n data: pandas.dataframe\n The data which shall be zoned\n return data: pandas.dataframe\n The zoning should return the imported dataset with an additional\n column called \"Zone\" which inhibits the\n information to which zone the respective room shall be part of.\n \"\"\"\n\n # account all outer walls not adjacent to the ambient to the entity\n # \"inner wall\"\n # !right now the wall construction of the added wall is not respected,\n # the same wall construction as regular\n # inner wall is set\n for index, line in data.iterrows():\n if not pd.isna(line[\"WallAdjacentTo\"]):\n data.at[index, \"InnerWallArea[m²]\"] = (\n data.at[index, \"OuterWallArea[m²]\"]\n + data.at[index, \"WindowArea[m²]\"]\n + data.at[index, \"InnerWallArea[m²]\"]\n )\n data.at[index, \"WindowOrientation[°]\"] = np.NaN\n data.at[index, \"WindowArea[m²]\"] = np.NaN\n data.at[index, \"WindowConstruction\"] = np.NaN\n data.at[index, \"OuterWallOrientation[°]\"] = np.NaN\n data.at[index, \"OuterWallArea[m²]\"] = np.NaN\n data.at[index, \"OuterWallConstruction\"] = np.NaN\n\n # make all rooms that belong to a certain room have the same room identifier\n _list = []\n for index, line in data.iterrows():\n if pd.isna(line[\"BelongsToIdentifier\"]):\n _list.append(line[\"RoomIdentifier\"])\n else:\n _list.append(line[\"BelongsToIdentifier\"])\n data[\"RoomCluster\"] = _list\n\n # check for lines in which the net area is zero, marking an second wall\n # or window\n # element for the respective room, and in which there is still stated a\n # UsageType which is wrong\n # and should be changed in the file\n for i, row in data.iterrows():\n if row[\"NetArea[m²]\"] == 0 and not pd.isna(row[\"UsageType\"]):\n warnings.warn(\n \"In line %s the net area is zero, marking an second wall or \"\n \"window element for the respective room, \"\n \"and in which there is still stated a UsageType which is \"\n \"wrong and should be changed in the file\" % i\n )\n\n # make all rooms of the cluster having the usage type of the main usage type\n _groups = data.groupby([\"RoomCluster\"])\n for index, cluster in _groups:\n count = 0\n for line in cluster.iterrows():\n if pd.isna(line[1][\"BelongsToIdentifier\"]) and not pd.isna(\n line[1][\"UsageType\"]\n ):\n main_usage = line[1][\"UsageType\"]\n for i, row in data.iterrows():\n if row[\"RoomCluster\"] == line[1][\"RoomCluster\"]:\n data.at[i, \"RoomClusterUsage\"] = main_usage\n count += 1\n if count != 1:\n warnings.warn(\n \"This cluster has more than one main usage type or none, \"\n \"check your excel file for mistakes! \\n\"\n \"Common mistakes: \\n\"\n \"-NetArea of a wall is not equal to 0 \\n\"\n \"-UsageType of a wall is not empty \\n\"\n \"Explanation: Rooms may have outer walls/windows on different orientations.\\n\"\n \"Every row with an empty slot in the column UsageType, \"\n \"marks another direction of an outer wall and/or\"\n \"window entity of the same room.\\n\"\n \"The connection of the same room is realised by an \"\n \"RoomIdentifier equal to the respective \"\n \"BelongsToIdentifier. \\n Cluster = %s\" % cluster\n )\n\n # name usage types after usage types available in the json\n usage_to_json_usage = {\n \"IsolationRoom\": \"Bed room\",\n \"PatientRoom\": \"Bed room\",\n \"Aisle\": \"Corridors in the general care area\",\n \"Technical room\": \"Stock, technical equipment, archives\",\n \"Washing\": \"WC and sanitary rooms in non-residential buildings\",\n \"Stairway\": \"Corridors in the general care area\",\n \"WC\": \"WC and sanitary rooms in non-residential buildings\",\n \"Storage\": \"Stock, technical equipment, archives\",\n \"Lounge\": \"Meeting, Conference, seminar\",\n \"Office\": \"Meeting, Conference, seminar\",\n \"Treatment room\": \"Examination- or treatment room\",\n \"StorageChemical\": \"Stock, technical equipment, archives\",\n \"EquipmentServiceAndRinse\": \"WC and sanitary rooms in non-residential buildings\",\n }\n\n # rename all zone names from the excel to the according zone name which\n # is in the UseConditions.json files\n usages = get_list_of_present_entries(data[\"RoomClusterUsage\"])\n for usage in usages:\n data[\"RoomClusterUsage\"] = np.where(\n data[\"RoomClusterUsage\"] == usage,\n usage_to_json_usage[usage],\n data[\"RoomClusterUsage\"],\n )\n\n # name the column where the zones are defined \"Zone\"\n data[\"Zone\"] = data[\"RoomClusterUsage\"]\n\n return data\n\n\n# -------------------------------------------------------------\ndef import_building_from_excel(\n project, building_name, construction_age, path_to_excel, sheet_names\n):\n \"\"\"\n Import building data from excel, convert it via the respective zoning and feed it to teasers logic classes.\n Pay attention to hard coded parts, which are marked.\n\n Parameters\n ----------\n project: Project()\n TEASER instance of Project\n building_name: str\n name of building to be set in the project\n construction_age: int [y]\n construction age of the building\n path_to_excel: str\n path to excel file to be imported\n sheet_names: str or list\n sheet names which shall be imported\n return data: pandas.DataFrame\n zoned DataFrame which is finally used to parametrize the teaser classes\n return project: Project()\n TEASER instance of Project filled with the imported building data\n \"\"\"\n\n def warn_constructiontype(element):\n \"\"\"Generic warning function\"\"\"\n if element.construction_type is None:\n warnings.warn(\n 'In zone \"%s\" the %s construction \"%s\" could not be loaded from the TypeBuildingElements.json, '\n \"an error will occur due to missing data for calculation.\"\n \"Check for spelling and the correct combination of building age and construction type.\"\n \"Here is the list of faulty entries:\\n%s\"\n \"\\nThese entries can easily be found checking the stated index in the produced ZonedInput.xlsx\"\n % (\n group[\"zone\"].iloc[0],\n element.name,\n group[\"OuterWallConstruction\"].iloc[0],\n group,\n )\n )\n\n bldg = Building(parent=project)\n bldg.name = building_name\n bldg.year_of_construction = construction_age\n bldg.with_ahu = True # HardCodedInput\n if bldg.with_ahu is True:\n bldg.central_ahu.heat_recovery = True # HardCodedInput\n bldg.central_ahu.efficiency_recovery = 0.35 # HardCodedInput\n bldg.central_ahu.temperature_profile = 25 * [273.15 + 18] # HardCodedInput\n bldg.central_ahu.min_relative_humidity_profile = 25 * [0] # HardCodedInput\n bldg.central_ahu.max_relative_humidity_profile = 25 * [1] # HardCodedInput\n bldg.central_ahu.v_flow_profile = 25 * [1] # HardCodedInput\n\n # Parameters that need hard coding in teasers logic classes\n # 1. \"use_set_back\" needs hard coding at aixlib.py in the init; defines\n # if the in the useconditions stated\n # heating_time with the respective set_back_temp should be applied.\n # use_set_back = false -> all hours of the day\n # have same set_temp_heat actual value: use_set_back = Check your current version!\n # 2. HeaterOn, CoolerOn, hHeat, lCool, etc. can be hard coded in the text\n # file\n # \"teaser / data / output / modelicatemplate / AixLib /\n # AixLib_ThermalZoneRecord_TwoElement\"\n # actual changes: Check your current version!\n\n # Parameters to be set for each and every zone (#HardCodedInput)\n # -----------------------------\n out_wall_tilt = 90\n window_tilt = 90\n ground_floor_tilt = 0\n floor_tilt = 0\n ceiling_tilt = 0\n rooftop_tilt = 0\n ground_floor_orientation = -2\n floor_orientation = -2\n rooftop_orientation = -1\n ceiling_orientation = -1\n # -----------------------------\n\n # load_building_data from excel_to_pandas DataFrame:\n data = import_data(path_to_excel, sheet_names)\n\n # informative print\n usage_types = get_list_of_present_entries(data[\"UsageType\"])\n print(\"List of present usage_types in the original Data set: \\n%s\" % usage_types)\n\n # define the zoning methodology/function\n data = zoning_example(data)\n\n # informative print\n usage_types = get_list_of_present_entries(data[\"Zone\"])\n print(\"List of zones after the zoning is applied: \\n%s\" % usage_types)\n\n # aggregate all rooms of each zone and for each set general parameter,\n # boundary conditions\n # and parameter regarding the building physics\n zones = data.groupby([\"Zone\"])\n for name, zone in zones:\n\n # Block: Thermal zone (general parameter)\n tz = ThermalZone(parent=bldg)\n tz.name = str(name)\n tz.area = zone[\"NetArea[m²]\"].sum()\n # room vice calculation of volume plus summing those\n tz.volume = (\n np.array(zone[\"NetArea[m²]\"]) * np.array(zone[\"HeatedRoomHeight[m]\"])\n ).sum()\n\n # Block: Boundary Conditions\n # load UsageOperationTime, Lighting, RoomClimate and InternalGains\n # from the \"UseCondition.json\"\n tz.use_conditions = UseConditions(parent=tz)\n tz.use_conditions.load_use_conditions(zone[\"Zone\"].iloc[0], project.data)\n\n # Block: Building Physics\n # Grouping by orientation and construction type\n # aggregating and feeding to the teaser logic classes\n grouped = zone.groupby([\"OuterWallOrientation[°]\", \"OuterWallConstruction\"])\n for name, group in grouped:\n # looping through a groupby object automatically discards the\n # groups where one of the attributes is nan\n # additionally check for strings, since the value must be of type\n # int or float\n if not isinstance(group[\"OuterWallOrientation[°]\"].iloc[0], str):\n out_wall = OuterWall(parent=tz)\n out_wall.name = (\n \"outer_wall_\"\n + str(int(group[\"OuterWallOrientation[°]\"].iloc[0]))\n + \"_\"\n + str(group[\"OuterWallConstruction\"].iloc[0])\n )\n out_wall.area = group[\"OuterWallArea[m²]\"].sum()\n out_wall.tilt = out_wall_tilt\n out_wall.orientation = group[\"OuterWallOrientation[°]\"].iloc[0]\n # load wall properties from \"TypeBuildingElements.json\"\n out_wall.load_type_element(\n year=bldg.year_of_construction,\n construction=group[\"OuterWallConstruction\"].iloc[0],\n )\n warn_constructiontype(out_wall)\n else:\n warnings.warn(\n 'In zone \"%s\" the OuterWallOrientation \"%s\" is '\n \"neither float nor int, \"\n \"hence this building element is not added.\\nHere is the \"\n \"list of faulty entries:\\n%s\"\n \"\\n These entries can easily be found checking the stated \"\n \"index in the produced ZonedInput.xlsx\"\n % (\n group[\"Zone\"].iloc[0],\n group[\"OuterWallOrientation[°]\"].iloc[0],\n group,\n )\n )\n\n grouped = zone.groupby([\"WindowOrientation[°]\", \"WindowConstruction\"])\n for name, group in grouped:\n # looping through a groupby object automatically discards the\n # groups where one of the attributes is nan\n # additionally check for strings, since the value must be of type\n # int or float\n if not isinstance(group[\"OuterWallOrientation[°]\"].iloc[0], str):\n window = Window(parent=tz)\n window.name = (\n \"window_\"\n + str(int(group[\"WindowOrientation[°]\"].iloc[0]))\n + \"_\"\n + str(group[\"WindowConstruction\"].iloc[0])\n )\n window.area = group[\"WindowArea[m²]\"].sum()\n window.tilt = window_tilt\n window.orientation = group[\"WindowOrientation[°]\"].iloc[0]\n # load wall properties from \"TypeBuildingElements.json\"\n window.load_type_element(\n year=bldg.year_of_construction,\n construction=group[\"WindowConstruction\"].iloc[0],\n )\n warn_constructiontype(window)\n else:\n warnings.warn(\n 'In zone \"%s\" the window orientation \"%s\" is neither '\n \"float nor int, \"\n \"hence this building element is not added. Here is the \"\n \"list of faulty entries:\\n%s\"\n \"\\nThese entries can easily be found checking the stated \"\n \"index in the produced ZonedInput.xlsx\"\n % (\n group[\"Zone\"].iloc[0],\n group[\"WindowOrientation[°]\"].iloc[0],\n group,\n )\n )\n\n grouped = zone.groupby([\"IsGroundFloor\", \"FloorConstruction\"])\n for name, group in grouped:\n if group[\"NetArea[m²]\"].sum() != 0: # to avoid devision by 0\n if group[\"IsGroundFloor\"].iloc[0] == 1:\n ground_floor = GroundFloor(parent=tz)\n ground_floor.name = \"ground_floor\" + str(\n group[\"FloorConstruction\"].iloc[0]\n )\n ground_floor.area = group[\"NetArea[m²]\"].sum()\n ground_floor.tilt = ground_floor_tilt\n ground_floor.orientation = ground_floor_orientation\n # load wall properties from \"TypeBuildingElements.json\"\n ground_floor.load_type_element(\n year=bldg.year_of_construction,\n construction=group[\"FloorConstruction\"].iloc[0],\n )\n warn_constructiontype(ground_floor)\n elif group[\"IsGroundFloor\"].iloc[0] == 0:\n floor = Floor(parent=tz)\n floor.name = \"floor\" + str(group[\"FloorConstruction\"].iloc[0])\n floor.area = group[\"NetArea[m²]\"].sum() / 2 # only half of\n # the floor belongs to this story\n floor.tilt = floor_tilt\n floor.orientation = floor_orientation\n # load wall properties from \"TypeBuildingElements.json\"\n floor.load_type_element(\n year=bldg.year_of_construction,\n construction=group[\"FloorConstruction\"].iloc[0],\n )\n warn_constructiontype(floor)\n else:\n warnings.warn(\n \"Values for IsGroundFloor have to be either 0 or 1, \"\n \"for no or yes respectively\"\n )\n else:\n warnings.warn(\n 'zone \"%s\" with IsGroundFloor \"%s\" and construction '\n 'type \"%s\" '\n \"has no floor nor groundfloor, since the area equals 0.\"\n % (\n group[\"Zone\"].iloc[0],\n group[\"IsGroundFloor\"].iloc[0],\n group[\"FloorConstruction\"].iloc[0],\n )\n )\n\n grouped = zone.groupby([\"IsRooftop\", \"CeilingConstruction\"])\n for name, group in grouped:\n if group[\"NetArea[m²]\"].sum() != 0: # to avoid devision by 0\n if group[\"IsRooftop\"].iloc[0] == 1:\n rooftop = Rooftop(parent=tz)\n rooftop.name = \"rooftop\" + str(group[\"CeilingConstruction\"].iloc[0])\n rooftop.area = group[\n \"NetArea[m²]\"\n ].sum() # sum up area of respective\n # rooftop parts\n rooftop.tilt = rooftop_tilt\n rooftop.orientation = rooftop_orientation\n # load wall properties from \"TypeBuildingElements.json\"\n rooftop.load_type_element(\n year=bldg.year_of_construction,\n construction=group[\"CeilingConstruction\"].iloc[0],\n )\n warn_constructiontype(rooftop)\n elif group[\"IsRooftop\"].iloc[0] == 0:\n ceiling = Ceiling(parent=tz)\n ceiling.name = \"ceiling\" + str(group[\"CeilingConstruction\"].iloc[0])\n ceiling.area = group[\"NetArea[m²]\"].sum() / 2 # only half\n # of the ceiling belongs to a story,\n # the other half to the above\n ceiling.tilt = ceiling_tilt\n ceiling.orientation = ceiling_orientation\n # load wall properties from \"TypeBuildingElements.json\"\n ceiling.load_type_element(\n year=bldg.year_of_construction,\n construction=group[\"CeilingConstruction\"].iloc[0],\n )\n warn_constructiontype(ceiling)\n else:\n warnings.warn(\n \"Values for IsRooftop have to be either 0 or 1, \"\n \"for no or yes respectively\"\n )\n else:\n warnings.warn(\n 'zone \"%s\" with IsRooftop \"%s\" and construction type '\n '\"%s\" '\n \"has no ceiling nor rooftop, since the area equals 0.\"\n % (\n group[\"Zone\"].iloc[0],\n group[\"IsRooftop\"].iloc[0],\n group[\"CeilingConstruction\"].iloc[0],\n )\n )\n\n grouped = zone.groupby([\"InnerWallConstruction\"])\n for name, group in grouped:\n if group[\"InnerWallArea[m²]\"].sum() != 0: # to avoid devision by 0\n in_wall = InnerWall(parent=tz)\n in_wall.name = \"inner_wall\" + str(\n group[\"InnerWallConstruction\"].iloc[0]\n )\n in_wall.area = group[\"InnerWallArea[m²]\"].sum() / 2 # only\n # half of the wall belongs to each room,\n # the other half to the adjacent\n # load wall properties from \"TypeBuildingElements.json\"\n in_wall.load_type_element(\n year=bldg.year_of_construction,\n construction=group[\"InnerWallConstruction\"].iloc[0],\n )\n warn_constructiontype(in_wall)\n else:\n warnings.warn(\n 'zone \"%s\" with inner wall construction \"%s\" has no '\n \"inner walls, since area = 0.\"\n % (group[\"Zone\"].iloc[0], group[\"InnerWallConstructio\" \"n\"].iloc[0])\n )\n\n # Block: AHU and infiltration #Attention hard coding\n # set the supply volume flow of the AHU per zone\n ahu_dict = {\n \"Bedroom\": [15.778, 15.778],\n \"Corridorsinthegeneralcarearea\": [5.2941, 5.2941],\n \"Examinationortreatmentroom\": [15.743, 15.743],\n \"MeetingConferenceseminar\": [16.036, 16.036],\n \"Stocktechnicalequipmentarchives\": [20.484, 20.484],\n \"WCandsanitaryroomsinnonresidentialbuildings\": [27.692, 27.692],\n }\n _i = 0\n for key in ahu_dict:\n if tz.name == key:\n tz.use_conditions.min_ahu = ahu_dict[key][0]\n tz.use_conditions.max_ahu = ahu_dict[key][1]\n _i = 1\n if _i == 0:\n warnings.warn(\n \"The zone %s could not be found in your ahu_dict. Hence, \"\n \"no AHU flow is defined. The default value is \"\n \"0 (min_ahu = 0; max_ahu=0\" % tz.name\n )\n\n return project, data\n\n\nif __name__ == \"__main__\":\n result_path = os.path.dirname(__file__)\n\n prj = Project(load_data=True)\n prj.name = \"BuildingGeneratedviaExcelImport\"\n prj.data.load_uc_binding()\n prj.weather_file_path = os.path.join(\n os.path.dirname(os.path.dirname(__file__)),\n \"data\",\n \"input\",\n \"inputdata\",\n \"weatherdata\",\n \"DEU_BW_Mannheim_107290_TRY2010_12_Jahr_BBSR.mos\",\n )\n prj.modelica_info.weekday = 0 # 0-Monday, 6-Sunday\n prj.modelica_info.simulation_start = 0 # start time for simulation\n\n PathToExcel = os.path.join(\n os.path.dirname(__file__), \"examplefiles\", \"ExcelBuildingData_Sample.xlsx\"\n )\n prj, Data = import_building_from_excel(\n prj, \"ExampleImport\", 2000, PathToExcel, sheet_names=[\"ImportSheet1\"]\n )\n\n prj.modelica_info.current_solver = \"dassl\"\n prj.calc_all_buildings(raise_errors=True)\n prj.export_aixlib(internal_id=None, path=result_path)\n\n # if wished, export the zoned DataFrame which is finally used to\n # parametrize the teaser classes\n Data.to_excel(os.path.join(result_path, prj.name, \"ZonedInput.xlsx\"))\n # if wished, save the current python script to the results folder to\n # track the used parameters and reproduce results\n shutil.copy(__file__, os.path.join(result_path, prj.name))\n\n print(\"%s: That's it :)\" % prj.name)\n"
] | [
[
"pandas.DataFrame",
"pandas.read_excel",
"numpy.array",
"numpy.where",
"pandas.isna"
]
] |
RDoerfel/mne-python | [
"46197d4926f4654dc1df2e0cabbfb26642fd884d"
] | [
"mne/io/write.py"
] | [
"# Authors: Alexandre Gramfort <[email protected]>\n# Matti Hämäläinen <[email protected]>\n#\n# License: BSD (3-clause)\n\nfrom gzip import GzipFile\nimport os.path as op\nimport re\nimport time\nimport uuid\n\nimport numpy as np\nfrom scipy import linalg, sparse\n\nfrom .constants import FIFF\nfrom ..fixes import _fn35\nfrom ..utils import logger, _file_like\nfrom ..utils.numerics import _cal_to_julian\n\n# We choose a \"magic\" date to store (because meas_date is obligatory)\n# to treat as meas_date=None. This one should be impossible for systems\n# to write -- the second field is microseconds, so anything >= 1e6\n# should be moved into the first field (seconds).\nDATE_NONE = (0, 2 ** 31 - 1)\n\n\ndef _write(fid, data, kind, data_size, FIFFT_TYPE, dtype):\n \"\"\"Write data.\"\"\"\n if isinstance(data, np.ndarray):\n data_size *= data.size\n\n # XXX for string types the data size is used as\n # computed in ``write_string``.\n\n fid.write(np.array(kind, dtype='>i4').tobytes())\n fid.write(np.array(FIFFT_TYPE, dtype='>i4').tobytes())\n fid.write(np.array(data_size, dtype='>i4').tobytes())\n fid.write(np.array(FIFF.FIFFV_NEXT_SEQ, dtype='>i4').tobytes())\n fid.write(np.array(data, dtype=dtype).tobytes())\n\n\ndef _get_split_size(split_size):\n \"\"\"Convert human-readable bytes to machine-readable bytes.\"\"\"\n if isinstance(split_size, str):\n exp = dict(MB=20, GB=30).get(split_size[-2:], None)\n if exp is None:\n raise ValueError('split_size has to end with either'\n '\"MB\" or \"GB\"')\n split_size = int(float(split_size[:-2]) * 2 ** exp)\n\n if split_size > 2147483648:\n raise ValueError('split_size cannot be larger than 2GB')\n return split_size\n\n\ndef write_nop(fid, last=False):\n \"\"\"Write a FIFF_NOP.\"\"\"\n fid.write(np.array(FIFF.FIFF_NOP, dtype='>i4').tobytes())\n fid.write(np.array(FIFF.FIFFT_VOID, dtype='>i4').tobytes())\n fid.write(np.array(0, dtype='>i4').tobytes())\n next_ = FIFF.FIFFV_NEXT_NONE if last else FIFF.FIFFV_NEXT_SEQ\n fid.write(np.array(next_, dtype='>i4').tobytes())\n\n\ndef write_int(fid, kind, data):\n \"\"\"Write a 32-bit integer tag to a fif file.\"\"\"\n data_size = 4\n data = np.array(data, dtype='>i4').T\n _write(fid, data, kind, data_size, FIFF.FIFFT_INT, '>i4')\n\n\ndef write_double(fid, kind, data):\n \"\"\"Write a double-precision floating point tag to a fif file.\"\"\"\n data_size = 8\n data = np.array(data, dtype='>f8').T\n _write(fid, data, kind, data_size, FIFF.FIFFT_DOUBLE, '>f8')\n\n\ndef write_float(fid, kind, data):\n \"\"\"Write a single-precision floating point tag to a fif file.\"\"\"\n data_size = 4\n data = np.array(data, dtype='>f4').T\n _write(fid, data, kind, data_size, FIFF.FIFFT_FLOAT, '>f4')\n\n\ndef write_dau_pack16(fid, kind, data):\n \"\"\"Write a dau_pack16 tag to a fif file.\"\"\"\n data_size = 2\n data = np.array(data, dtype='>i2').T\n _write(fid, data, kind, data_size, FIFF.FIFFT_DAU_PACK16, '>i2')\n\n\ndef write_complex64(fid, kind, data):\n \"\"\"Write a 64 bit complex floating point tag to a fif file.\"\"\"\n data_size = 8\n data = np.array(data, dtype='>c8').T\n _write(fid, data, kind, data_size, FIFF.FIFFT_COMPLEX_FLOAT, '>c8')\n\n\ndef write_complex128(fid, kind, data):\n \"\"\"Write a 128 bit complex floating point tag to a fif file.\"\"\"\n data_size = 16\n data = np.array(data, dtype='>c16').T\n _write(fid, data, kind, data_size, FIFF.FIFFT_COMPLEX_FLOAT, '>c16')\n\n\ndef write_julian(fid, kind, data):\n \"\"\"Write a Julian-formatted date to a FIF file.\"\"\"\n assert len(data) == 3\n data_size = 4\n jd = np.sum(_cal_to_julian(*data))\n data = np.array(jd, dtype='>i4')\n _write(fid, data, kind, data_size, FIFF.FIFFT_JULIAN, '>i4')\n\n\ndef write_string(fid, kind, data):\n \"\"\"Write a string tag.\"\"\"\n str_data = data.encode('latin1')\n data_size = len(str_data) # therefore compute size here\n my_dtype = '>a' # py2/3 compatible on writing -- don't ask me why\n if data_size > 0:\n _write(fid, str_data, kind, data_size, FIFF.FIFFT_STRING, my_dtype)\n\n\ndef write_name_list(fid, kind, data):\n \"\"\"Write a colon-separated list of names.\n\n Parameters\n ----------\n data : list of strings\n \"\"\"\n write_string(fid, kind, ':'.join(data))\n\n\ndef write_float_matrix(fid, kind, mat):\n \"\"\"Write a single-precision floating-point matrix tag.\"\"\"\n FIFFT_MATRIX = 1 << 30\n FIFFT_MATRIX_FLOAT = FIFF.FIFFT_FLOAT | FIFFT_MATRIX\n\n data_size = 4 * mat.size + 4 * (mat.ndim + 1)\n\n fid.write(np.array(kind, dtype='>i4').tobytes())\n fid.write(np.array(FIFFT_MATRIX_FLOAT, dtype='>i4').tobytes())\n fid.write(np.array(data_size, dtype='>i4').tobytes())\n fid.write(np.array(FIFF.FIFFV_NEXT_SEQ, dtype='>i4').tobytes())\n fid.write(np.array(mat, dtype='>f4').tobytes())\n\n dims = np.empty(mat.ndim + 1, dtype=np.int32)\n dims[:mat.ndim] = mat.shape[::-1]\n dims[-1] = mat.ndim\n fid.write(np.array(dims, dtype='>i4').tobytes())\n check_fiff_length(fid)\n\n\ndef write_double_matrix(fid, kind, mat):\n \"\"\"Write a double-precision floating-point matrix tag.\"\"\"\n FIFFT_MATRIX = 1 << 30\n FIFFT_MATRIX_DOUBLE = FIFF.FIFFT_DOUBLE | FIFFT_MATRIX\n\n data_size = 8 * mat.size + 4 * (mat.ndim + 1)\n\n fid.write(np.array(kind, dtype='>i4').tobytes())\n fid.write(np.array(FIFFT_MATRIX_DOUBLE, dtype='>i4').tobytes())\n fid.write(np.array(data_size, dtype='>i4').tobytes())\n fid.write(np.array(FIFF.FIFFV_NEXT_SEQ, dtype='>i4').tobytes())\n fid.write(np.array(mat, dtype='>f8').tobytes())\n\n dims = np.empty(mat.ndim + 1, dtype=np.int32)\n dims[:mat.ndim] = mat.shape[::-1]\n dims[-1] = mat.ndim\n fid.write(np.array(dims, dtype='>i4').tobytes())\n check_fiff_length(fid)\n\n\ndef write_int_matrix(fid, kind, mat):\n \"\"\"Write integer 32 matrix tag.\"\"\"\n FIFFT_MATRIX = 1 << 30\n FIFFT_MATRIX_INT = FIFF.FIFFT_INT | FIFFT_MATRIX\n\n data_size = 4 * mat.size + 4 * 3\n\n fid.write(np.array(kind, dtype='>i4').tobytes())\n fid.write(np.array(FIFFT_MATRIX_INT, dtype='>i4').tobytes())\n fid.write(np.array(data_size, dtype='>i4').tobytes())\n fid.write(np.array(FIFF.FIFFV_NEXT_SEQ, dtype='>i4').tobytes())\n fid.write(np.array(mat, dtype='>i4').tobytes())\n\n dims = np.empty(3, dtype=np.int32)\n dims[0] = mat.shape[1]\n dims[1] = mat.shape[0]\n dims[2] = 2\n fid.write(np.array(dims, dtype='>i4').tobytes())\n check_fiff_length(fid)\n\n\ndef write_complex_float_matrix(fid, kind, mat):\n \"\"\"Write complex 64 matrix tag.\"\"\"\n FIFFT_MATRIX = 1 << 30\n FIFFT_MATRIX_COMPLEX_FLOAT = FIFF.FIFFT_COMPLEX_FLOAT | FIFFT_MATRIX\n\n data_size = 4 * 2 * mat.size + 4 * (mat.ndim + 1)\n\n fid.write(np.array(kind, dtype='>i4').tobytes())\n fid.write(np.array(FIFFT_MATRIX_COMPLEX_FLOAT, dtype='>i4').tobytes())\n fid.write(np.array(data_size, dtype='>i4').tobytes())\n fid.write(np.array(FIFF.FIFFV_NEXT_SEQ, dtype='>i4').tobytes())\n fid.write(np.array(mat, dtype='>c8').tobytes())\n\n dims = np.empty(mat.ndim + 1, dtype=np.int32)\n dims[:mat.ndim] = mat.shape[::-1]\n dims[-1] = mat.ndim\n fid.write(np.array(dims, dtype='>i4').tobytes())\n check_fiff_length(fid)\n\n\ndef write_complex_double_matrix(fid, kind, mat):\n \"\"\"Write complex 128 matrix tag.\"\"\"\n FIFFT_MATRIX = 1 << 30\n FIFFT_MATRIX_COMPLEX_DOUBLE = FIFF.FIFFT_COMPLEX_DOUBLE | FIFFT_MATRIX\n\n data_size = 8 * 2 * mat.size + 4 * (mat.ndim + 1)\n\n fid.write(np.array(kind, dtype='>i4').tobytes())\n fid.write(np.array(FIFFT_MATRIX_COMPLEX_DOUBLE, dtype='>i4').tobytes())\n fid.write(np.array(data_size, dtype='>i4').tobytes())\n fid.write(np.array(FIFF.FIFFV_NEXT_SEQ, dtype='>i4').tobytes())\n fid.write(np.array(mat, dtype='>c16').tobytes())\n\n dims = np.empty(mat.ndim + 1, dtype=np.int32)\n dims[:mat.ndim] = mat.shape[::-1]\n dims[-1] = mat.ndim\n fid.write(np.array(dims, dtype='>i4').tobytes())\n check_fiff_length(fid)\n\n\ndef get_machid():\n \"\"\"Get (mostly) unique machine ID.\n\n Returns\n -------\n ids : array (length 2, int32)\n The machine identifier used in MNE.\n \"\"\"\n mac = b'%012x' % uuid.getnode() # byte conversion for Py3\n mac = re.findall(b'..', mac) # split string\n mac += [b'00', b'00'] # add two more fields\n\n # Convert to integer in reverse-order (for some reason)\n from codecs import encode\n mac = b''.join([encode(h, 'hex_codec') for h in mac[::-1]])\n ids = np.flipud(np.frombuffer(mac, np.int32, count=2))\n return ids\n\n\ndef get_new_file_id():\n \"\"\"Create a new file ID tag.\"\"\"\n secs, usecs = divmod(time.time(), 1.)\n secs, usecs = int(secs), int(usecs * 1e6)\n return {'machid': get_machid(), 'version': FIFF.FIFFC_VERSION,\n 'secs': secs, 'usecs': usecs}\n\n\ndef write_id(fid, kind, id_=None):\n \"\"\"Write fiff id.\"\"\"\n id_ = _generate_meas_id() if id_ is None else id_\n\n data_size = 5 * 4 # The id comprises five integers\n fid.write(np.array(kind, dtype='>i4').tobytes())\n fid.write(np.array(FIFF.FIFFT_ID_STRUCT, dtype='>i4').tobytes())\n fid.write(np.array(data_size, dtype='>i4').tobytes())\n fid.write(np.array(FIFF.FIFFV_NEXT_SEQ, dtype='>i4').tobytes())\n\n # Collect the bits together for one write\n arr = np.array([id_['version'],\n id_['machid'][0], id_['machid'][1],\n id_['secs'], id_['usecs']], dtype='>i4')\n fid.write(arr.tobytes())\n\n\ndef start_block(fid, kind):\n \"\"\"Write a FIFF_BLOCK_START tag.\"\"\"\n write_int(fid, FIFF.FIFF_BLOCK_START, kind)\n\n\ndef end_block(fid, kind):\n \"\"\"Write a FIFF_BLOCK_END tag.\"\"\"\n write_int(fid, FIFF.FIFF_BLOCK_END, kind)\n\n\ndef start_file(fname, id_=None):\n \"\"\"Open a fif file for writing and writes the compulsory header tags.\n\n Parameters\n ----------\n fname : string | fid\n The name of the file to open. It is recommended\n that the name ends with .fif or .fif.gz. Can also be an\n already opened file.\n id_ : dict | None\n ID to use for the FIFF_FILE_ID.\n \"\"\"\n if _file_like(fname):\n logger.debug('Writing using %s I/O' % type(fname))\n fid = fname\n fid.seek(0)\n else:\n fname = _fn35(fname)\n if op.splitext(fname)[1].lower() == '.gz':\n logger.debug('Writing using gzip')\n # defaults to compression level 9, which is barely smaller but much\n # slower. 2 offers a good compromise.\n fid = GzipFile(fname, \"wb\", compresslevel=2)\n else:\n logger.debug('Writing using normal I/O')\n fid = open(fname, \"wb\")\n # Write the compulsory items\n write_id(fid, FIFF.FIFF_FILE_ID, id_)\n write_int(fid, FIFF.FIFF_DIR_POINTER, -1)\n write_int(fid, FIFF.FIFF_FREE_LIST, -1)\n return fid\n\n\ndef check_fiff_length(fid, close=True):\n \"\"\"Ensure our file hasn't grown too large to work properly.\"\"\"\n if fid.tell() > 2147483648: # 2 ** 31, FIFF uses signed 32-bit locations\n if close:\n fid.close()\n raise IOError('FIFF file exceeded 2GB limit, please split file or '\n 'save to a different format')\n\n\ndef end_file(fid):\n \"\"\"Write the closing tags to a fif file and closes the file.\"\"\"\n write_nop(fid, last=True)\n check_fiff_length(fid)\n fid.close()\n\n\ndef write_coord_trans(fid, trans):\n \"\"\"Write a coordinate transformation structure.\"\"\"\n data_size = 4 * 2 * 12 + 4 * 2\n fid.write(np.array(FIFF.FIFF_COORD_TRANS, dtype='>i4').tobytes())\n fid.write(np.array(FIFF.FIFFT_COORD_TRANS_STRUCT, dtype='>i4').tobytes())\n fid.write(np.array(data_size, dtype='>i4').tobytes())\n fid.write(np.array(FIFF.FIFFV_NEXT_SEQ, dtype='>i4').tobytes())\n fid.write(np.array(trans['from'], dtype='>i4').tobytes())\n fid.write(np.array(trans['to'], dtype='>i4').tobytes())\n\n # The transform...\n rot = trans['trans'][:3, :3]\n move = trans['trans'][:3, 3]\n fid.write(np.array(rot, dtype='>f4').tobytes())\n fid.write(np.array(move, dtype='>f4').tobytes())\n\n # ...and its inverse\n trans_inv = linalg.inv(trans['trans'])\n rot = trans_inv[:3, :3]\n move = trans_inv[:3, 3]\n fid.write(np.array(rot, dtype='>f4').tobytes())\n fid.write(np.array(move, dtype='>f4').tobytes())\n\n\ndef write_ch_info(fid, ch):\n \"\"\"Write a channel information record to a fif file.\"\"\"\n data_size = 4 * 13 + 4 * 7 + 16\n\n fid.write(np.array(FIFF.FIFF_CH_INFO, dtype='>i4').tobytes())\n fid.write(np.array(FIFF.FIFFT_CH_INFO_STRUCT, dtype='>i4').tobytes())\n fid.write(np.array(data_size, dtype='>i4').tobytes())\n fid.write(np.array(FIFF.FIFFV_NEXT_SEQ, dtype='>i4').tobytes())\n\n # Start writing fiffChInfoRec\n fid.write(np.array(ch['scanno'], dtype='>i4').tobytes())\n fid.write(np.array(ch['logno'], dtype='>i4').tobytes())\n fid.write(np.array(ch['kind'], dtype='>i4').tobytes())\n fid.write(np.array(ch['range'], dtype='>f4').tobytes())\n fid.write(np.array(ch['cal'], dtype='>f4').tobytes())\n fid.write(np.array(ch['coil_type'], dtype='>i4').tobytes())\n fid.write(np.array(ch['loc'], dtype='>f4').tobytes()) # writing 12 values\n\n # unit and unit multiplier\n fid.write(np.array(ch['unit'], dtype='>i4').tobytes())\n fid.write(np.array(ch['unit_mul'], dtype='>i4').tobytes())\n\n # Finally channel name\n ch_name = ch['ch_name'][:15]\n fid.write(np.array(ch_name, dtype='>c').tobytes())\n fid.write(b'\\0' * (16 - len(ch_name)))\n\n\ndef write_dig_points(fid, dig, block=False, coord_frame=None):\n \"\"\"Write a set of digitizer data points into a fif file.\"\"\"\n if dig is not None:\n data_size = 5 * 4\n if block:\n start_block(fid, FIFF.FIFFB_ISOTRAK)\n if coord_frame is not None:\n write_int(fid, FIFF.FIFF_MNE_COORD_FRAME, coord_frame)\n for d in dig:\n fid.write(np.array(FIFF.FIFF_DIG_POINT, '>i4').tobytes())\n fid.write(np.array(FIFF.FIFFT_DIG_POINT_STRUCT, '>i4').tobytes())\n fid.write(np.array(data_size, dtype='>i4').tobytes())\n fid.write(np.array(FIFF.FIFFV_NEXT_SEQ, '>i4').tobytes())\n # Start writing fiffDigPointRec\n fid.write(np.array(d['kind'], '>i4').tobytes())\n fid.write(np.array(d['ident'], '>i4').tobytes())\n fid.write(np.array(d['r'][:3], '>f4').tobytes())\n if block:\n end_block(fid, FIFF.FIFFB_ISOTRAK)\n\n\ndef write_float_sparse_rcs(fid, kind, mat):\n \"\"\"Write a single-precision sparse compressed row matrix tag.\"\"\"\n return write_float_sparse(fid, kind, mat, fmt='csr')\n\n\ndef write_float_sparse_ccs(fid, kind, mat):\n \"\"\"Write a single-precision sparse compressed column matrix tag.\"\"\"\n return write_float_sparse(fid, kind, mat, fmt='csc')\n\n\ndef write_float_sparse(fid, kind, mat, fmt='auto'):\n \"\"\"Write a single-precision floating-point sparse matrix tag.\"\"\"\n from .tag import _matrix_coding_CCS, _matrix_coding_RCS\n if fmt == 'auto':\n fmt = 'csr' if isinstance(mat, sparse.csr_matrix) else 'csc'\n if fmt == 'csr':\n need = sparse.csr_matrix\n bits = _matrix_coding_RCS\n else:\n need = sparse.csc_matrix\n bits = _matrix_coding_CCS\n if not isinstance(mat, need):\n raise TypeError('Must write %s, got %s' % (fmt.upper(), type(mat),))\n FIFFT_MATRIX = bits << 16\n FIFFT_MATRIX_FLOAT_RCS = FIFF.FIFFT_FLOAT | FIFFT_MATRIX\n\n nnzm = mat.nnz\n nrow = mat.shape[0]\n data_size = 4 * nnzm + 4 * nnzm + 4 * (nrow + 1) + 4 * 4\n\n fid.write(np.array(kind, dtype='>i4').tobytes())\n fid.write(np.array(FIFFT_MATRIX_FLOAT_RCS, dtype='>i4').tobytes())\n fid.write(np.array(data_size, dtype='>i4').tobytes())\n fid.write(np.array(FIFF.FIFFV_NEXT_SEQ, dtype='>i4').tobytes())\n\n fid.write(np.array(mat.data, dtype='>f4').tobytes())\n fid.write(np.array(mat.indices, dtype='>i4').tobytes())\n fid.write(np.array(mat.indptr, dtype='>i4').tobytes())\n\n dims = [nnzm, mat.shape[0], mat.shape[1], 2]\n fid.write(np.array(dims, dtype='>i4').tobytes())\n check_fiff_length(fid)\n\n\ndef _generate_meas_id():\n \"\"\"Generate a new meas_id dict.\"\"\"\n id_ = dict()\n id_['version'] = FIFF.FIFFC_VERSION\n id_['machid'] = get_machid()\n id_['secs'], id_['usecs'] = DATE_NONE\n return id_\n"
] | [
[
"numpy.array",
"numpy.empty",
"numpy.frombuffer",
"scipy.linalg.inv"
]
] |
rahmani15/dimod | [
"4e5918dbf35ad02d4ddcc022c8c94b47d91978bd"
] | [
"dimod/generators/constraints.py"
] | [
"# Copyright 2019 D-Wave Systems Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport collections.abc as abc\n\nimport numpy as np\n\nfrom dimod.binary_quadratic_model import BinaryQuadraticModel\nfrom dimod.decorators import graph_argument, vartype_argument\nfrom dimod.vartypes import BINARY\n\n__all__ = 'combinations',\n\n\ndef combinations(n, k, strength=1, vartype=BINARY):\n r\"\"\"Generate a BQM that is minimized when k of n variables are selected.\n\n More fully, generates a binary quadratic model (BQM) that is minimized for\n each of the k-combinations of its variables.\n\n The energy for the BQM is given by\n :math:`(\\sum_{i} x_i - k)^2`.\n\n Args:\n n (int/list/set):\n If n is an integer, variables are labelled [0, n-1]. If n is a list\n or set, variables are labelled accordingly.\n\n k (int):\n The generated BQM has 0 energy when any k of its variables are 1.\n\n strength (number, optional, default=1):\n The energy of the first excited state of the BQM.\n\n vartype (:class:`.Vartype`/str/set):\n Variable type for the BQM. Accepted input values:\n\n * :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``\n * :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``\n\n Returns:\n :obj:`.BinaryQuadraticModel`\n\n Examples:\n\n >>> bqm = dimod.generators.combinations(['a', 'b', 'c'], 2)\n >>> bqm.energy({'a': 1, 'b': 0, 'c': 1})\n 0.0\n >>> bqm.energy({'a': 1, 'b': 1, 'c': 1})\n 1.0\n\n >>> bqm = dimod.generators.combinations(5, 1)\n >>> bqm.energy({0: 0, 1: 0, 2: 1, 3: 0, 4: 0})\n 0.0\n >>> bqm.energy({0: 0, 1: 0, 2: 1, 3: 1, 4: 0})\n 1.0\n\n >>> bqm = dimod.generators.combinations(['a', 'b', 'c'], 2, strength=3.0)\n >>> bqm.energy({'a': 1, 'b': 0, 'c': 1})\n 0.0\n >>> bqm.energy({'a': 1, 'b': 1, 'c': 1})\n 3.0\n\n \"\"\"\n if isinstance(n, abc.Sized) and isinstance(n, abc.Iterable):\n # what we actually want is abc.Collection but that doesn't exist in\n # python2\n variables = n\n else:\n try:\n variables = range(n)\n except TypeError:\n raise TypeError('n should be a collection or an integer')\n\n if k > len(variables) or k < 0:\n raise ValueError(\"cannot select k={} from {} variables\".format(k, len(variables)))\n\n # (\\sum_i x_i - k)^2\n # = \\sum_i x_i \\sum_j x_j - 2k\\sum_i x_i + k^2\n # = \\sum_{i,j} x_ix_j + (1 - 2k)\\sum_i x_i + k^2\n lbias = float(strength*(1 - 2*k))\n qbias = float(2*strength)\n\n if not isinstance(n, int):\n num_vars = len(n)\n variables = n\n else:\n num_vars = n\n try:\n variables = range(n)\n except TypeError:\n raise TypeError('n should be a collection or an integer')\n\n Q = np.triu(np.ones((num_vars,num_vars))*qbias, k=1)\n np.fill_diagonal(Q, lbias)\n bqm = BinaryQuadraticModel.from_qubo(Q, offset=strength*(k**2))\n\n if not isinstance(n, int):\n bqm.relabel_variables(dict(zip(range(len(n)), n)))\n\n return bqm.change_vartype(vartype, inplace=True)\n"
] | [
[
"numpy.ones",
"numpy.fill_diagonal"
]
] |
kakainet/TexSet | [
"95c09724893a275b46a12d7b5ef2ae211203a2aa"
] | [
"dataset/bbox_gen.py"
] | [
"import cv2\nimport numpy as np\nimport argparse\nimport os\nimport json\n\n\ndef iswhite(p):\n return p[0] > 180 and p[1] > 180 and p[2] > 180\n\n\ndef convert(o):\n if isinstance(o, np.int64):\n return int(o)\n else:\n return o\n\n\ndef avgcolor(img):\n total = [0, 0, 0]\n ctr = 0\n eps = int(0.1 * sum(img.shape)/len(img.shape))\n rows, cols, _ = img.shape\n for i in range(eps, rows - eps):\n for j in range(eps, cols - eps):\n p = img[i, j]\n if not iswhite(p):\n for c in range(3):\n total[c] = total[c] + p[c]\n ctr = ctr+1\n\n if ctr == 0:\n return [0, 0, 0]\n return [total[j]/ctr for j in range(3)]\n\n\ndef process_img(in_dir, out_dir, name):\n image = cv2.imread(os.path.join(in_dir, name))\n x,y,c = image.shape\n assert(c==3)\n\n # get all pixels which are gray\n gray_detector = np.zeros((x,y,1))\n\n for i in range(x):\n for j in range(y):\n b,g,r=[image[i,j,p] for p in range(3)]\n gray_detector[i,j] = min(int(abs(int(b)-int(g)))+\n int(abs(int(b)-int(r)))+\n int(abs(int(g)-int(r))),\n 255)\n\n image2 = image.copy()\n image2= np.where(gray_detector > 5, image2, 255)\n gray = 255 - cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)\n boxes = {}\n for i in range(8):\n boxes[i] = []\n cnts = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_KCOS)\n cnts = cnts[0] if len(cnts) == 2 else cnts[1]\n for k, c in enumerate(cnts):\n x, y, w, h = cv2.boundingRect(c)\n subimg = image[y:y+h, x:x+w]\n c = avgcolor(subimg)\n hashcode = sum([(c[j] > 220) * (2**j) for j in range(3)])\n boxes[hashcode].append([x, y, x+w, y+h])\n bboxes = []\n for k in sorted(boxes.keys()):\n if not boxes[k] or k == 0: # colour not present or colour is black (== operator)\n continue\n m = 0\n\n perchannel = np.array(boxes[k]).transpose()\n xmin, ymin = np.min(perchannel[0]), np.min(perchannel[1])\n xmaks, ymaks = np.max(perchannel[2]), np.max(perchannel[3])\n bboxes.append([xmin, ymin, xmaks-xmin, ymaks-ymin])\n color = list(np.random.random(size=3) * 256)\n cv2.rectangle(image, (xmin, ymin), (xmaks, ymaks), color, 1)\n\n annotations.append(\n {'name': name, 'op': '', 'exprs': sorted(bboxes)})\n\n cv2.imwrite(os.path.join(out_dir, name), image)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--in-dir', help='input directory',\n required=True, type=str)\n parser.add_argument('--out-dir', help='output directory',\n required=True, type=str)\n parser.add_argument('--save', help='save file', required=False, type=str)\n\n args = parser.parse_args()\n input_names = os.listdir(args.in_dir)\n\n if not os.path.exists(args.out_dir):\n os.mkdir(args.out_dir)\n\n annotations = []\n\n for name in input_names:\n process_img(args.in_dir, args.out_dir, name)\n json_output = json.dumps(annotations, default=convert)\n\n if not args.save:\n print(json_output)\n else:\n with open(args.save, 'w+') as savefile:\n savefile.write(json_output)\n"
] | [
[
"numpy.zeros",
"numpy.random.random",
"numpy.max",
"numpy.min",
"numpy.array",
"numpy.where"
]
] |
zzx9636/cross-view | [
"9a7e874be607eefa7bd34934e274cc376e99f65f"
] | [
"train_argo.py"
] | [
"import os\nimport random\nimport time\nimport numpy as np\nimport torch\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nfrom crossView import PVA_model, Argoverse\nfrom opt import get_args\nimport tqdm\nfrom datetime import datetime\n\n\nfrom utils import mean_IU, mean_precision\nimport wandb\n\n\ndef readlines(filename):\n \"\"\"Read all the lines in a text file and return as a list\n \"\"\"\n with open(filename, 'r') as f:\n lines = f.read().splitlines()\n return lines\n\n\nclass Trainer_argo:\n def __init__(self):\n self.opt = get_args()\n self.models = {}\n self.weight = {\"static\": self.opt.static_weight, \"dynamic\": self.opt.dynamic_weight}\n self.seed = self.opt.global_seed\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\n self.create_time = time.strftime(\"%Y-%m-%d-%H-%M\", time.localtime())\n self.epoch = 0\n self.start_epoch = 0\n \n if self.seed != 0:\n self.set_seed() # set seed\n\n # Initializing models\n self.model = PVA_model(self.opt, self.device)\n #self.model.to(self.device)\n\n # Optimization\n self.optimizer = optim.Adam(self.model.parameters_to_train)\n \n # Data Loaders\n fpath = os.path.join(\n os.path.dirname(__file__),\n \"splits\",\n \"argo\",\n \"{}_files.txt\")\n\n train_filenames = readlines(fpath.format(\"train\"))\n val_filenames = readlines(fpath.format(\"val\"))\n self.val_filenames = val_filenames\n self.train_filenames = train_filenames\n\n train_dataset = Argoverse(self.opt, train_filenames)\n val_dataset = Argoverse(self.opt, val_filenames, is_train=False)\n\n self.train_loader = DataLoader(\n dataset = train_dataset,\n batch_size = self.opt.batch_size,\n shuffle = True,\n num_workers=self.opt.num_workers,\n pin_memory=True,\n drop_last=True)\n \n self.val_loader = DataLoader(\n dataset = val_dataset,\n batch_size = 1,\n shuffle = True,\n num_workers=self.opt.num_workers,\n pin_memory=True,\n drop_last=True)\n\n if self.opt.load_weights_folder != \"\":\n self.load_model()\n \n # Save log and models path\n now = datetime.now()\n\n self.opt.save_path = os.path.join(self.opt.save_path, now.strftime(\"%Y%m%d-%H%M%S\"))\n wandb.init(project=\"cross-view\", entity=\"zzx9636\", config={\"epochs\": self.opt.num_epochs, \n \"batch_size\": self.opt.batch_size})\n\n wandb.define_metric(\"eval/*\", step_metric=\"eval/step\")\n\n print(\n \"There are {:d} training items and {:d} validation items\\n\".format(\n len(train_dataset),\n len(val_dataset)))\n\n def train(self):\n #self.validation()\n for self.epoch in range(self.start_epoch, self.opt.num_epochs + 1):\n self.adjust_learning_rate(self.optimizer, self.epoch, self.opt.lr_steps)\n self.run_epoch()\n self.validation()\n if (self.epoch%5)==0:\n self.save_model()\n\n def run_epoch(self):\n for inputs in self.train_loader:\n self.model.train()\n self.optimizer.zero_grad()\n for key, input in inputs.items():\n if key != \"filename\":\n inputs[key] = input.to(self.device)\n _, losses = self.model(inputs)\n losses[\"loss\"].backward()\n self.optimizer.step()\n \n wandb.log({\"loss\": losses[\"loss\"], \"topview_loss\": losses[\"topview_loss\"], \n \"transform_loss\": losses[\"transform_loss\"]}) \n #\"transform_topview_loss\": losses[\"transform_topview_loss\"]})\n\n def validation(self):\n iou, mAP = np.array([0., 0., 0.]), np.array([0., 0., 0.])\n #trans_iou, trans_mAP = np.array([0., 0.]), np.array([0., 0.])\n with torch.no_grad():\n for inputs in self.val_loader:\n \n self.model.eval()\n for key, input in inputs.items():\n if key != \"filename\":\n inputs[key] = input.to(self.device)\n outputs, _ = self.model(inputs)\n pred = np.squeeze(\n torch.argmax(\n outputs[\"topview\"].detach(),\n 1).cpu().numpy())\n true = np.squeeze(\n inputs[\"combine\"].detach().cpu().numpy())\n #print(mean_IU(pred, true), mean_precision(pred, true))\n iou += mean_IU(pred, true)\n mAP += mean_precision(pred, true)\n iou /= len(self.val_loader)\n mAP /= len(self.val_loader)\n print(\"Epoch: %d | Validation: mIOU: %.4f, %.4f mAP: %.4f, %.4f\" % (self.epoch, iou[1], iou[2], mAP[1], mAP[2]))\n \n log_dict = {\"eval/step\": self.epoch, \"eval/map/mIOU\": iou[1], \"eval/map/mAP\": mAP[1],\n \"eval/vehicle/mIOU\": iou[2], \"eval/vehicle/mAP\": mAP[2]}\n wandb.log(log_dict)\n \n\n def save_model(self):\n save_path = os.path.join(\n self.opt.save_path,\n \"weights_{}\".format(\n self.epoch)\n )\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n\n for model_name, model in self.model.models.items():\n model_path = os.path.join(save_path, \"{}.pth\".format(model_name))\n state_dict = model.state_dict()\n state_dict['epoch'] = self.epoch\n if model_name == \"encoder\":\n state_dict[\"height\"] = self.opt.height\n state_dict[\"width\"] = self.opt.width\n\n torch.save(state_dict, model_path)\n optim_path = os.path.join(save_path, \"{}.pth\".format(\"adam\"))\n torch.save(self.optimizer.state_dict(), optim_path)\n print(\"Save models to \", save_path)\n\n def load_model(self):\n \"\"\"Load model(s) from disk\n \"\"\"\n self.opt.load_weights_folder = os.path.expanduser(\n self.opt.load_weights_folder)\n\n assert os.path.isdir(self.opt.load_weights_folder), \\\n \"Cannot find folder {}\".format(self.opt.load_weights_folder)\n print(\n \"loading model from folder {}\".format(\n self.opt.load_weights_folder))\n\n for key in self.model.models.keys():\n if \"discriminator\" not in key:\n print(\"Loading {} weights...\".format(key))\n path = os.path.join(\n self.opt.load_weights_folder,\n \"{}.pth\".format(key))\n model_dict = self.model.models[key].state_dict()\n pretrained_dict = torch.load(path)\n if 'epoch' in pretrained_dict:\n self.start_epoch = pretrained_dict['epoch']\n pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}\n model_dict.update(pretrained_dict)\n self.model.models[key].load_state_dict(model_dict)\n\n # loading adam state\n if self.opt.load_weights_folder == \"\":\n optimizer_load_path = os.path.join(\n self.opt.load_weights_folder, \"adam.pth\")\n if os.path.isfile(optimizer_load_path):\n print(\"Loading Adam weights\")\n optimizer_dict = torch.load(optimizer_load_path)\n self.optimizer.load_state_dict(optimizer_dict)\n else:\n print(\"Cannot find Adam weights so Adam is randomly initialized\")\n\n def adjust_learning_rate(self, optimizer, epoch, lr_steps):\n \"\"\"Sets the learning rate to the initial LR decayed by 10 every 25 epochs\"\"\"\n decay = 0.1 ** (sum(epoch >= np.array(lr_steps)))\n decay = round(decay, 2)\n lr = self.opt.lr * decay\n lr_transform = self.opt.lr_transform * decay\n decay = self.opt.weight_decay\n optimizer.param_groups[0]['lr'] = lr_transform\n optimizer.param_groups[1]['lr'] = lr\n optimizer.param_groups[0]['weight_decay'] = decay\n optimizer.param_groups[1]['weight_decay'] = decay\n wandb.log({\"lr\": lr, \"lr_transform\":lr_transform, \"decay\": decay})\n\n\n def set_seed(self):\n seed = self.seed\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n\n\nif __name__ == \"__main__\":\n start_time = time.ctime()\n print(start_time)\n trainer = Trainer_argo()\n trainer.train()\n end_time = time.ctime()\n print(end_time)\n"
] | [
[
"torch.utils.data.DataLoader",
"torch.cuda.manual_seed_all",
"torch.load",
"torch.cuda.manual_seed",
"torch.manual_seed",
"torch.no_grad",
"numpy.random.seed",
"torch.save",
"torch.optim.Adam",
"torch.cuda.is_available",
"numpy.array"
]
] |
elielhojman/tensorflow | [
"89e06304aad35bfb019a8c10f39fc1ead83e0f99"
] | [
"tensorflow/python/training/optimizer.py"
] | [
"# Copyright 2015 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\n\"\"\"Base class for optimizers.\"\"\"\n# pylint: disable=g-bad-name\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport abc\n\nfrom tensorflow.python.eager import backprop\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import gradients\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import resource_variable_ops\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.training import distribute as distribute_lib\nfrom tensorflow.python.training import slot_creator\nfrom tensorflow.python.training.checkpointable import base as checkpointable\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.util.tf_export import tf_export\n\n\ndef get_filtered_grad_fn(grad_fn):\n # `distributed_context.join()` requires that its arguments are parallel\n # across threads, and in particular that `grads_and_vars` has the same\n # variables in the same order.\n\n # When computing gradients in eager mode with multiple threads, you\n # can get extra variables with a gradient of `None`. This happens when\n # those variables are accessed in another thread during the gradient\n # computation. To get a consistent set of variables, we filter out\n # those with `None` gradients.\n def filtered_grad_fn(x=None):\n return [(g, v) for g, v in grad_fn(x) if g is not None]\n\n return filtered_grad_fn\n\n\ndef _deduplicate_indexed_slices(values, indices):\n \"\"\"Sums `values` associated with any non-unique `indices`.\n\n Args:\n values: A `Tensor` with rank >= 1.\n indices: A one-dimensional integer `Tensor`, indexing into the first\n dimension of `values` (as in an IndexedSlices object).\n Returns:\n A tuple of (`summed_values`, `unique_indices`) where `unique_indices` is a\n de-duplicated version of `indices` and `summed_values` contains the sum of\n `values` slices associated with each unique index.\n \"\"\"\n unique_indices, new_index_positions = array_ops.unique(indices)\n summed_values = math_ops.unsorted_segment_sum(\n values, new_index_positions,\n array_ops.shape(unique_indices)[0])\n return (summed_values, unique_indices)\n\n\ndef _var_key(var):\n # TODO(ashankar): Consolidate handling for eager and graph\n if hasattr(var, \"op\"):\n return (var.op.graph, var.op.name)\n return var._unique_id # pylint: disable=protected-access\n\n\nclass _OptimizableVariable(object):\n \"\"\"Interface for abstracting over variables in the optimizers.\"\"\"\n\n @abc.abstractmethod\n def target(self):\n \"\"\"Returns the optimization target for this variable.\"\"\"\n raise NotImplementedError(\"Calling an abstract method.\")\n\n @abc.abstractmethod\n def update_op(self, optimizer, g):\n \"\"\"Returns the update ops for updating the variable.\"\"\"\n raise NotImplementedError(\"Calling an abstract method.\")\n\n\nclass _RefVariableProcessor(_OptimizableVariable):\n \"\"\"Processor for Variable.\"\"\"\n\n def __init__(self, v):\n self._v = v\n\n def __str__(self):\n return \"<_RefVariableProcessor(%s)>\" % self._v\n\n def target(self):\n return self._v._ref() # pylint: disable=protected-access\n\n def update_op(self, optimizer, g):\n if isinstance(g, ops.Tensor):\n update_op = optimizer._apply_dense(g, self._v) # pylint: disable=protected-access\n if self._v.constraint is not None:\n with ops.control_dependencies([update_op]):\n return self._v.assign(self._v.constraint(self._v))\n else:\n return update_op\n else:\n assert isinstance(g, ops.IndexedSlices), (\"Gradient \", g, \" is neither a \"\n \"tensor nor IndexedSlices.\")\n if self._v.constraint is not None:\n raise RuntimeError(\n \"Cannot use a constraint function on a sparse variable.\")\n # pylint: disable=protected-access\n return optimizer._apply_sparse_duplicate_indices(g, self._v)\n\n\nclass _DenseReadResourceVariableProcessor(_OptimizableVariable):\n \"\"\"Processor for dense ResourceVariables.\"\"\"\n\n def __init__(self, v):\n self._v = v\n\n def target(self):\n return self._v\n\n def update_op(self, optimizer, g):\n # pylint: disable=protected-access\n update_op = optimizer._resource_apply_dense(g, self._v.op.inputs[0])\n if self._v.constraint is not None:\n with ops.control_dependencies([update_op]):\n return self._v.assign(self._v.constraint(self._v))\n else:\n return update_op\n\n\nclass _DenseResourceVariableProcessor(_OptimizableVariable):\n \"\"\"Processor for dense ResourceVariables.\"\"\"\n\n def __init__(self, v):\n self._v = v\n\n def target(self):\n return self._v\n\n def update_op(self, optimizer, g):\n # pylint: disable=protected-access\n if isinstance(g, ops.IndexedSlices):\n if self._v.constraint is not None:\n raise RuntimeError(\n \"Cannot use a constraint function on a sparse variable.\")\n return optimizer._resource_apply_sparse_duplicate_indices(\n g.values, self._v, g.indices)\n update_op = optimizer._resource_apply_dense(g, self._v)\n if self._v.constraint is not None:\n with ops.control_dependencies([update_op]):\n return self._v.assign(self._v.constraint(self._v))\n else:\n return update_op\n\n\nclass _TensorProcessor(_OptimizableVariable):\n \"\"\"Processor for ordinary Tensors.\n\n Even though a Tensor can't really be updated, sometimes it is useful to\n compute the gradients with respect to a Tensor using the optimizer. Updating\n the Tensor is, of course, unsupported.\n \"\"\"\n\n def __init__(self, v):\n self._v = v\n\n def target(self):\n return self._v\n\n def update_op(self, optimizer, g):\n raise NotImplementedError(\"Trying to update a Tensor \", self._v)\n\n\ndef _get_processor(v):\n \"\"\"The processor of v.\"\"\"\n if context.executing_eagerly():\n if isinstance(v, ops.Tensor):\n return _TensorProcessor(v)\n else:\n return _DenseResourceVariableProcessor(v)\n if isinstance(\n v, resource_variable_ops.ResourceVariable) and not v._in_graph_mode: # pylint: disable=protected-access\n # True if and only if `v` was initialized eagerly.\n return _DenseResourceVariableProcessor(v)\n if v.op.type == \"VarHandleOp\":\n return _DenseResourceVariableProcessor(v)\n if isinstance(v, variables.Variable):\n return _RefVariableProcessor(v)\n if isinstance(v, ops.Tensor):\n return _TensorProcessor(v)\n raise NotImplementedError(\"Trying to optimize unsupported type \", v)\n\n\n@tf_export(\"train.Optimizer\")\nclass Optimizer(\n # Optimizers inherit from CheckpointableBase rather than Checkpointable\n # since they do most of their dependency management themselves (slot\n # variables are special-cased, and non-slot variables are keyed to graphs).\n checkpointable.CheckpointableBase):\n \"\"\"Base class for optimizers.\n\n This class defines the API to add Ops to train a model. You never use this\n class directly, but instead instantiate one of its subclasses such as\n `GradientDescentOptimizer`, `AdagradOptimizer`, or `MomentumOptimizer`.\n\n ### Usage\n\n ```python\n # Create an optimizer with the desired parameters.\n opt = GradientDescentOptimizer(learning_rate=0.1)\n # Add Ops to the graph to minimize a cost by updating a list of variables.\n # \"cost\" is a Tensor, and the list of variables contains tf.Variable\n # objects.\n opt_op = opt.minimize(cost, var_list=<list of variables>)\n ```\n\n In the training program you will just have to run the returned Op.\n\n ```python\n # Execute opt_op to do one step of training:\n opt_op.run()\n ```\n\n ### Processing gradients before applying them.\n\n Calling `minimize()` takes care of both computing the gradients and\n applying them to the variables. If you want to process the gradients\n before applying them you can instead use the optimizer in three steps:\n\n 1. Compute the gradients with `compute_gradients()`.\n 2. Process the gradients as you wish.\n 3. Apply the processed gradients with `apply_gradients()`.\n\n Example:\n\n ```python\n # Create an optimizer.\n opt = GradientDescentOptimizer(learning_rate=0.1)\n\n # Compute the gradients for a list of variables.\n grads_and_vars = opt.compute_gradients(loss, <list of variables>)\n\n # grads_and_vars is a list of tuples (gradient, variable). Do whatever you\n # need to the 'gradient' part, for example cap them, etc.\n capped_grads_and_vars = [(MyCapper(gv[0]), gv[1]) for gv in grads_and_vars]\n\n # Ask the optimizer to apply the capped gradients.\n opt.apply_gradients(capped_grads_and_vars)\n ```\n\n ### Gating Gradients\n\n Both `minimize()` and `compute_gradients()` accept a `gate_gradients`\n argument that controls the degree of parallelism during the application of\n the gradients.\n\n The possible values are: `GATE_NONE`, `GATE_OP`, and `GATE_GRAPH`.\n\n <b>`GATE_NONE`</b>: Compute and apply gradients in parallel. This provides\n the maximum parallelism in execution, at the cost of some non-reproducibility\n in the results. For example the two gradients of `matmul` depend on the input\n values: With `GATE_NONE` one of the gradients could be applied to one of the\n inputs _before_ the other gradient is computed resulting in non-reproducible\n results.\n\n <b>`GATE_OP`</b>: For each Op, make sure all gradients are computed before\n they are used. This prevents race conditions for Ops that generate gradients\n for multiple inputs where the gradients depend on the inputs.\n\n <b>`GATE_GRAPH`</b>: Make sure all gradients for all variables are computed\n before any one of them is used. This provides the least parallelism but can\n be useful if you want to process all gradients before applying any of them.\n\n ### Slots\n\n Some optimizer subclasses, such as `MomentumOptimizer` and `AdagradOptimizer`\n allocate and manage additional variables associated with the variables to\n train. These are called <i>Slots</i>. Slots have names and you can ask the\n optimizer for the names of the slots that it uses. Once you have a slot name\n you can ask the optimizer for the variable it created to hold the slot value.\n\n This can be useful if you want to log debug a training algorithm, report stats\n about the slots, etc.\n \"\"\"\n\n # Values for gate_gradients.\n GATE_NONE = 0\n GATE_OP = 1\n GATE_GRAPH = 2\n\n def __init__(self, use_locking, name):\n \"\"\"Create a new Optimizer.\n\n This must be called by the constructors of subclasses.\n\n Args:\n use_locking: Bool. If True apply use locks to prevent concurrent updates\n to variables.\n name: A non-empty string. The name to use for accumulators created\n for the optimizer.\n\n Raises:\n ValueError: If name is malformed.\n \"\"\"\n if not name:\n raise ValueError(\"Must specify the optimizer name\")\n self._use_locking = use_locking\n self._name = name\n # Dictionary of slots.\n # {slot_name :\n # {_var_key(variable_to_train): slot_for_the_variable, ... },\n # ... }\n self._slots = {}\n self._non_slot_dict = {}\n # For implementing Checkpointable. Stores information about how to restore\n # slot variables which have not yet been created\n # (checkpointable._CheckpointPosition objects).\n # {slot_name :\n # {_var_key(variable_to_train): [checkpoint_position, ... ], ... },\n # ... }\n self._deferred_slot_restorations = {}\n\n # TODO(isaprykin): When using a DistributionStrategy, and when an\n # optimizer is created in each tower, it might be dangerous to\n # rely on some Optimer methods. When such methods are called on a\n # per-tower optimizer, an exception needs to be thrown. We do\n # allow creation per-tower optimizers however, because the\n # compute_gradients()->apply_gradients() sequence is safe.\n\n def get_name(self):\n return self._name\n\n def minimize(self, loss, global_step=None, var_list=None,\n gate_gradients=GATE_OP, aggregation_method=None,\n colocate_gradients_with_ops=False, name=None,\n grad_loss=None):\n \"\"\"Add operations to minimize `loss` by updating `var_list`.\n\n This method simply combines calls `compute_gradients()` and\n `apply_gradients()`. If you want to process the gradient before applying\n them call `compute_gradients()` and `apply_gradients()` explicitly instead\n of using this function.\n\n Args:\n loss: A `Tensor` containing the value to minimize.\n global_step: Optional `Variable` to increment by one after the\n variables have been updated.\n var_list: Optional list or tuple of `Variable` objects to update to\n minimize `loss`. Defaults to the list of variables collected in\n the graph under the key `GraphKeys.TRAINABLE_VARIABLES`.\n gate_gradients: How to gate the computation of gradients. Can be\n `GATE_NONE`, `GATE_OP`, or `GATE_GRAPH`.\n aggregation_method: Specifies the method used to combine gradient terms.\n Valid values are defined in the class `AggregationMethod`.\n colocate_gradients_with_ops: If True, try colocating gradients with\n the corresponding op.\n name: Optional name for the returned operation.\n grad_loss: Optional. A `Tensor` holding the gradient computed for `loss`.\n\n Returns:\n An Operation that updates the variables in `var_list`. If `global_step`\n was not `None`, that operation also increments `global_step`.\n\n Raises:\n ValueError: If some of the variables are not `Variable` objects.\n\n @compatibility(eager)\n When eager execution is enabled, `loss` should be a Python function that\n takes elements of `var_list` as arguments and computes the value to be\n minimized. If `var_list` is None, `loss` should take no arguments.\n Minimization (and gradient computation) is done with respect to the\n elements of `var_list` if not None, else with respect to any trainable\n variables created during the execution of the `loss` function.\n `gate_gradients`, `aggregation_method`, `colocate_gradients_with_ops` and\n `grad_loss` are ignored when eager execution is enabled.\n @end_compatibility\n \"\"\"\n grads_and_vars = self.compute_gradients(\n loss, var_list=var_list, gate_gradients=gate_gradients,\n aggregation_method=aggregation_method,\n colocate_gradients_with_ops=colocate_gradients_with_ops,\n grad_loss=grad_loss)\n\n vars_with_grad = [v for g, v in grads_and_vars if g is not None]\n if not vars_with_grad:\n raise ValueError(\n \"No gradients provided for any variable, check your graph for ops\"\n \" that do not support gradients, between variables %s and loss %s.\" %\n ([str(v) for _, v in grads_and_vars], loss))\n\n return self.apply_gradients(grads_and_vars, global_step=global_step,\n name=name)\n\n def compute_gradients(self, loss, var_list=None,\n gate_gradients=GATE_OP,\n aggregation_method=None,\n colocate_gradients_with_ops=False,\n grad_loss=None):\n \"\"\"Compute gradients of `loss` for the variables in `var_list`.\n\n This is the first part of `minimize()`. It returns a list\n of (gradient, variable) pairs where \"gradient\" is the gradient\n for \"variable\". Note that \"gradient\" can be a `Tensor`, an\n `IndexedSlices`, or `None` if there is no gradient for the\n given variable.\n\n Args:\n loss: A Tensor containing the value to minimize or a callable taking\n no arguments which returns the value to minimize. When eager execution\n is enabled it must be a callable.\n var_list: Optional list or tuple of `tf.Variable` to update to minimize\n `loss`. Defaults to the list of variables collected in the graph\n under the key `GraphKeys.TRAINABLE_VARIABLES`.\n gate_gradients: How to gate the computation of gradients. Can be\n `GATE_NONE`, `GATE_OP`, or `GATE_GRAPH`.\n aggregation_method: Specifies the method used to combine gradient terms.\n Valid values are defined in the class `AggregationMethod`.\n colocate_gradients_with_ops: If True, try colocating gradients with\n the corresponding op.\n grad_loss: Optional. A `Tensor` holding the gradient computed for `loss`.\n\n Returns:\n A list of (gradient, variable) pairs. Variable is always present, but\n gradient can be `None`.\n\n Raises:\n TypeError: If `var_list` contains anything else than `Variable` objects.\n ValueError: If some arguments are invalid.\n RuntimeError: If called with eager execution enabled and `loss` is\n not callable.\n\n @compatibility(eager)\n When eager execution is enabled, `gate_gradients`, `aggregation_method`,\n and `colocate_gradients_with_ops` are ignored.\n @end_compatibility\n \"\"\"\n if callable(loss):\n with backprop.GradientTape() as tape:\n if var_list is not None:\n tape.watch(var_list)\n loss_value = loss()\n\n # Scale loss if using a \"mean\" loss reduction and multiple towers.\n # Have to be careful to call distribute_lib.get_loss_reduction()\n # *after* loss() is evaluated, so we know what loss reduction it uses.\n # TODO(josh11b): Test that we handle weight decay in a reasonable way.\n if (distribute_lib.get_loss_reduction() ==\n variable_scope.VariableAggregation.MEAN):\n num_towers = distribute_lib.get_distribution_strategy().num_towers\n if num_towers > 1:\n loss_value *= (1. / num_towers)\n\n if var_list is None:\n var_list = tape.watched_variables()\n grads = tape.gradient(loss_value, var_list, grad_loss)\n return list(zip(grads, var_list))\n\n # Non-callable/Tensor loss case\n if context.executing_eagerly():\n raise RuntimeError(\n \"`loss` passed to Optimizer.compute_gradients should \"\n \"be a function when eager execution is enabled.\")\n\n # Scale loss if using a \"mean\" loss reduction and multiple towers.\n if (distribute_lib.get_loss_reduction() ==\n variable_scope.VariableAggregation.MEAN):\n num_towers = distribute_lib.get_distribution_strategy().num_towers\n if num_towers > 1:\n loss *= (1. / num_towers)\n\n if gate_gradients not in [Optimizer.GATE_NONE, Optimizer.GATE_OP,\n Optimizer.GATE_GRAPH]:\n raise ValueError(\"gate_gradients must be one of: Optimizer.GATE_NONE, \"\n \"Optimizer.GATE_OP, Optimizer.GATE_GRAPH. Not %s\" %\n gate_gradients)\n self._assert_valid_dtypes([loss])\n if grad_loss is not None:\n self._assert_valid_dtypes([grad_loss])\n if var_list is None:\n var_list = (\n variables.trainable_variables() +\n ops.get_collection(ops.GraphKeys.TRAINABLE_RESOURCE_VARIABLES))\n else:\n var_list = nest.flatten(var_list)\n # pylint: disable=protected-access\n var_list += ops.get_collection(ops.GraphKeys._STREAMING_MODEL_PORTS)\n # pylint: enable=protected-access\n processors = [_get_processor(v) for v in var_list]\n if not var_list:\n raise ValueError(\"No variables to optimize.\")\n var_refs = [p.target() for p in processors]\n grads = gradients.gradients(\n loss, var_refs, grad_ys=grad_loss,\n gate_gradients=(gate_gradients == Optimizer.GATE_OP),\n aggregation_method=aggregation_method,\n colocate_gradients_with_ops=colocate_gradients_with_ops)\n if gate_gradients == Optimizer.GATE_GRAPH:\n grads = control_flow_ops.tuple(grads)\n grads_and_vars = list(zip(grads, var_list))\n self._assert_valid_dtypes(\n [v for g, v in grads_and_vars\n if g is not None and v.dtype != dtypes.resource])\n return grads_and_vars\n\n def apply_gradients(self, grads_and_vars, global_step=None, name=None):\n \"\"\"Apply gradients to variables.\n\n This is the second part of `minimize()`. It returns an `Operation` that\n applies gradients.\n\n Args:\n grads_and_vars: List of (gradient, variable) pairs as returned by\n `compute_gradients()`.\n global_step: Optional `Variable` to increment by one after the\n variables have been updated.\n name: Optional name for the returned operation. Default to the\n name passed to the `Optimizer` constructor.\n\n Returns:\n An `Operation` that applies the specified gradients. If `global_step`\n was not None, that operation also increments `global_step`.\n\n Raises:\n TypeError: If `grads_and_vars` is malformed.\n ValueError: If none of the variables have gradients.\n RuntimeError: If you should use `_distributed_apply()` instead.\n \"\"\"\n # This is a default implementation of apply_gradients() that can be shared\n # by most optimizers. It relies on the subclass implementing the following\n # methods: _create_slots(), _prepare(), _apply_dense(), and _apply_sparse().\n\n # Handle DistributionStrategy case.\n if distribute_lib.get_cross_tower_context():\n raise RuntimeError(\"Use `_distributed_apply()` instead of \"\n \"`apply_gradients()` in a cross-tower context.\")\n # TODO(isaprykin): Get rid of `has_distribution_strategy()` check by\n # always calling _distributed_apply(), using the default distribution\n # as needed.\n if distribute_lib.has_distribution_strategy():\n grads_and_vars = get_filtered_grad_fn(lambda _: grads_and_vars)()\n return distribute_lib.get_tower_context().merge_call(\n self._distributed_apply, grads_and_vars, global_step, name)\n\n # No DistributionStrategy case.\n grads_and_vars = tuple(grads_and_vars) # Make sure repeat iteration works.\n if not grads_and_vars:\n raise ValueError(\"No variables provided.\")\n converted_grads_and_vars = []\n for g, v in grads_and_vars:\n if g is not None:\n try:\n # Convert the grad to Tensor or IndexedSlices if necessary.\n g = ops.convert_to_tensor_or_indexed_slices(g)\n except TypeError:\n raise TypeError(\n \"Gradient must be convertible to a Tensor\"\n \" or IndexedSlices, or None: %s\" % g)\n if not isinstance(g, (ops.Tensor, ops.IndexedSlices)):\n raise TypeError(\n \"Gradient must be a Tensor, IndexedSlices, or None: %s\" % g)\n p = _get_processor(v)\n converted_grads_and_vars.append((g, v, p))\n\n converted_grads_and_vars = tuple(converted_grads_and_vars)\n var_list = [v for g, v, _ in converted_grads_and_vars if g is not None]\n if not var_list:\n raise ValueError(\"No gradients provided for any variable: %s.\" %\n ([str(v) for _, _, v in converted_grads_and_vars],))\n with ops.init_scope():\n self._create_slots(var_list)\n update_ops = []\n with ops.name_scope(name, self._name) as name:\n self._prepare()\n for grad, var, processor in converted_grads_and_vars:\n if grad is None:\n continue\n # We colocate all ops created in _apply_dense or _apply_sparse\n # on the same device as the variable.\n # TODO(apassos): figure out how to get the variable name here.\n if context.executing_eagerly() or isinstance(\n var,\n resource_variable_ops.ResourceVariable) and not var._in_graph_mode: # pylint: disable=protected-access\n scope_name = \"\"\n else:\n scope_name = var.op.name\n with ops.name_scope(\"update_\" + scope_name), ops.colocate_with(var):\n update_ops.append(processor.update_op(self, grad))\n if global_step is None:\n apply_updates = self._finish(update_ops, name)\n else:\n with ops.control_dependencies([self._finish(update_ops, \"update\")]):\n with ops.colocate_with(global_step):\n if isinstance(global_step, resource_variable_ops.ResourceVariable):\n # TODO(apassos): the implicit read in assign_add is slow; consider\n # making it less so.\n apply_updates = resource_variable_ops.assign_add_variable_op(\n global_step.handle,\n ops.convert_to_tensor(1, dtype=global_step.dtype),\n name=name)\n else:\n apply_updates = state_ops.assign_add(global_step, 1, name=name)\n\n if not context.executing_eagerly():\n if isinstance(apply_updates, ops.Tensor):\n apply_updates = apply_updates.op\n train_op = ops.get_collection_ref(ops.GraphKeys.TRAIN_OP)\n if apply_updates not in train_op:\n train_op.append(apply_updates)\n\n return apply_updates\n\n def _distributed_apply(self,\n distribution,\n grads_and_vars,\n global_step=None,\n name=None):\n \"\"\"A version of `apply_gradients` for cross-tower context.\n\n This is a version of `apply_gradients()` for when you are using a\n `DistributionStrategy` and are in a cross-tower context. If in a\n tower context, use `apply_gradients()` as normal.\n\n Args:\n distribution: A `DistributionStrategy` object.\n grads_and_vars: List of (gradient, variable) pairs as returned by\n `compute_gradients()`, and then aggregated across towers.\n global_step: Optional (mirrored) `Variable` to increment by one\n after the variables have been updated.\n name: Optional name for the returned operation. Default to the\n name passed to the `Optimizer` constructor.\n\n Returns:\n An `Operation` that applies the specified gradients across all\n towers. If `global_step` was not None, that operation also\n increments `global_step`.\n \"\"\"\n reduced_grads = distribution.batch_reduce(\n variable_scope.VariableAggregation.SUM, grads_and_vars)\n var_list = [v for _, v in grads_and_vars]\n grads_and_vars = zip(reduced_grads, var_list)\n # Note that this is called in a cross-tower context.\n self._create_slots(var_list)\n\n def update(v, g):\n \"\"\"Apply gradients to a replica variable.\"\"\"\n assert v is not None\n\n try:\n # Convert the grad to Tensor or IndexedSlices if necessary.\n g = ops.convert_to_tensor_or_indexed_slices(g)\n except TypeError:\n raise TypeError(\"Gradient must be convertible to a Tensor\"\n \" or IndexedSlices, or None: %s\" % g)\n if not isinstance(g, (ops.Tensor, ops.IndexedSlices)):\n raise TypeError(\n \"Gradient must be a Tensor, IndexedSlices, or None: %s\" % g)\n p = _get_processor(v)\n\n scope_name = \"\" if context.executing_eagerly() else v.op.name\n # device_policy is set because non-mirrored tensors will be read in\n # `update_op`. `_resource_apply_dense`, `lr_t`, `beta1_t` and `beta2_t`\n # is an example.\n with ops.name_scope(\"update_\" + scope_name):\n return p.update_op(self, g)\n\n with ops.name_scope(name, self._name) as name:\n self._prepare()\n\n update_ops = [\n op\n for grad, var in grads_and_vars\n for op in distribution.unwrap(distribution.update(var, update, grad))\n ]\n\n def finish(self, update_ops):\n return self._finish(update_ops, \"update\")\n\n non_slot_devices = distribution.non_slot_devices(var_list)\n finish_updates = distribution.update_non_slot(\n non_slot_devices, finish, self, update_ops)\n if global_step is None:\n apply_updates = distribution.group(finish_updates, name=name)\n else:\n with ops.control_dependencies(distribution.unwrap(finish_updates)):\n apply_updates = distribution.group(distribution.update(\n global_step, state_ops.assign_add, 1, name=name))\n\n if not context.executing_eagerly():\n if isinstance(apply_updates, ops.Tensor):\n apply_updates = apply_updates.op\n train_op = ops.get_collection_ref(ops.GraphKeys.TRAIN_OP)\n if apply_updates not in train_op:\n train_op.append(apply_updates)\n\n return apply_updates\n\n def get_slot(self, var, name):\n \"\"\"Return a slot named `name` created for `var` by the Optimizer.\n\n Some `Optimizer` subclasses use additional variables. For example\n `Momentum` and `Adagrad` use variables to accumulate updates. This method\n gives access to these `Variable` objects if for some reason you need them.\n\n Use `get_slot_names()` to get the list of slot names created by the\n `Optimizer`.\n\n Args:\n var: A variable passed to `minimize()` or `apply_gradients()`.\n name: A string.\n\n Returns:\n The `Variable` for the slot if it was created, `None` otherwise.\n \"\"\"\n # pylint: disable=protected-access\n named_slots = self._slots.get(name, None)\n if not named_slots:\n return None\n\n if hasattr(var, \"_distributed_container\"):\n # NOTE: If this isn't patched, then there is no `handle` in\n # `_resource_apply_dense`.\n distributed_container = var._distributed_container()\n assert distributed_container is not None\n if context.executing_eagerly():\n key = distributed_container._unique_id\n else:\n key = (distributed_container.graph, distributed_container._shared_name)\n # pylint: enable=protected-access\n mirrored_slot = named_slots.get(key, None)\n if mirrored_slot is None: return None\n return mirrored_slot.get(device=var.device)\n\n return named_slots.get(_var_key(var), None)\n\n def get_slot_names(self):\n \"\"\"Return a list of the names of slots created by the `Optimizer`.\n\n See `get_slot()`.\n\n Returns:\n A list of strings.\n \"\"\"\n return sorted(self._slots.keys())\n\n def variables(self):\n \"\"\"A list of variables which encode the current state of `Optimizer`.\n\n Includes slot variables and additional global variables created by the\n optimizer in the current default graph.\n\n Returns:\n A list of variables.\n \"\"\"\n executing_eagerly = context.executing_eagerly()\n current_graph = ops.get_default_graph()\n\n def _from_current_graph(variable):\n if executing_eagerly:\n # No variable.op in eager mode. We don't expect lots of eager graphs,\n # but behavior should be consistent with graph mode.\n return variable._graph_key == current_graph._graph_key # pylint: disable=protected-access\n else:\n return variable.op.graph is current_graph\n\n optimizer_variables = [v for v in self._non_slot_variables()\n if _from_current_graph(v)]\n for _, variable_dict in self._slots.items():\n for _, slot_for_variable in variable_dict.items():\n if _from_current_graph(slot_for_variable):\n optimizer_variables.append(slot_for_variable)\n # Sort variables by name so that the return is deterministic.\n return sorted(optimizer_variables, key=lambda v: v.name)\n\n def _create_non_slot_variable(self, initial_value, name, colocate_with):\n \"\"\"Add an extra variable, not associated with a slot.\"\"\"\n # Recommendation: Use OptimizerV2 if your optimizer uses non-slot variables.\n eager = context.executing_eagerly()\n graph = None if eager else colocate_with.graph\n\n key = (name, graph)\n v = self._non_slot_dict.get(key, None)\n if v is None:\n self._maybe_initialize_checkpointable()\n distribution_strategy = distribute_lib.get_distribution_strategy()\n with distribution_strategy.colocate_vars_with(colocate_with):\n if eager:\n restored_initial_value = self._preload_simple_restoration(\n name=name, shape=None)\n if restored_initial_value is not None:\n initial_value = restored_initial_value\n v = variable_scope.variable(initial_value, name=name, trainable=False)\n # Restore this variable by name if necessary, but don't add a\n # Checkpointable dependency. Optimizers return the current graph's\n # non-slot variables from _checkpoint_dependencies explicitly rather\n # than unconditionally adding dependencies (since there may be multiple\n # non-slot variables with the same name in different graphs, trying to\n # save all of them would result in errors).\n self._handle_deferred_dependencies(name=name, checkpointable=v)\n self._non_slot_dict[key] = v\n\n return v\n\n @property\n def _checkpoint_dependencies(self):\n \"\"\"From Checkpointable. Gather graph-specific non-slot variables to save.\"\"\"\n current_graph_non_slot_variables = []\n current_graph_key = ops.get_default_graph()._graph_key # pylint: disable=protected-access\n for (name, _), variable_object in sorted(self._non_slot_dict.items(),\n # Avoid comparing graphs\n key=lambda item: item[0][0]):\n if variable_object._graph_key == current_graph_key: # pylint: disable=protected-access\n current_graph_non_slot_variables.append(\n checkpointable.CheckpointableReference(\n name=name, ref=variable_object))\n return (super(Optimizer, self)._checkpoint_dependencies\n + current_graph_non_slot_variables)\n\n def _lookup_dependency(self, name):\n \"\"\"From Checkpointable. Find a non-slot variable in the current graph.\"\"\"\n unconditional = super(Optimizer, self)._lookup_dependency(name)\n if unconditional is not None:\n return unconditional\n graph = None if context.executing_eagerly() else ops.get_default_graph()\n return self._get_non_slot_variable(name, graph=graph)\n\n def _get_non_slot_variable(self, name, graph=None):\n non_slot = self._non_slot_dict.get((name, graph), None)\n if hasattr(non_slot, \"_distributed_container\"):\n # This is a mirrored non-slot. In order to enable code like `_finish`\n # to assign to a non-slot, return the current context replica.\n return non_slot.get()\n else:\n return non_slot\n\n def _non_slot_variables(self):\n \"\"\"Additional variables created by the `Optimizer`.\n\n Returns:\n A list or tuple of variables.\n \"\"\"\n return self._non_slot_dict.values()\n\n def _assert_valid_dtypes(self, tensors):\n \"\"\"Asserts tensors are all valid types (see `_valid_dtypes`).\n\n Args:\n tensors: Tensors to check.\n\n Raises:\n ValueError: If any tensor is not a valid type.\n \"\"\"\n valid_dtypes = self._valid_dtypes()\n for t in tensors:\n dtype = t.dtype.base_dtype\n if dtype not in valid_dtypes:\n raise ValueError(\n \"Invalid type %r for %s, expected: %s.\" % (\n dtype, t.name, [v for v in valid_dtypes]))\n\n # --------------\n # Methods to be implemented by subclasses if they want to use the\n # inherited implementation of apply_gradients() or compute_gradients().\n # --------------\n def _valid_dtypes(self):\n \"\"\"Valid types for loss, variables and gradients.\n\n Subclasses should override to allow other float types.\n\n Returns:\n Valid types for loss, variables and gradients.\n \"\"\"\n return set(\n [dtypes.float16, dtypes.bfloat16, dtypes.float32, dtypes.float64])\n\n def _create_slots(self, var_list):\n \"\"\"Create all slots needed by the variables.\n\n Args:\n var_list: A list of `Variable` objects.\n \"\"\"\n # No slots needed by default\n pass\n\n def _prepare(self):\n \"\"\"Create all needed tensors before applying gradients.\n\n This is called with the name_scope using the \"name\" that\n users have chosen for the application of gradients.\n \"\"\"\n pass\n\n def _apply_dense(self, grad, var):\n \"\"\"Add ops to apply dense gradients to `var`.\n\n Args:\n grad: A `Tensor`.\n var: A `Variable` object.\n\n Returns:\n An `Operation`.\n \"\"\"\n raise NotImplementedError()\n\n def _resource_apply_dense(self, grad, handle):\n \"\"\"Add ops to apply dense gradients to the variable `handle`.\n\n Args:\n grad: a `Tensor` representing the gradient.\n handle: a `Tensor` of dtype `resource` which points to the variable\n to be updated.\n\n Returns:\n An `Operation` which updates the value of the variable.\n \"\"\"\n raise NotImplementedError()\n\n def _resource_apply_sparse_duplicate_indices(self, grad, handle, indices):\n \"\"\"Add ops to apply sparse gradients to `handle`, with repeated indices.\n\n Optimizers which override this method must deal with repeated indices. See\n the docstring of `_apply_sparse_duplicate_indices` for details. By default\n the correct behavior, to sum non-unique indices and their associated\n gradients, is enforced by first pre-processing `grad` and `indices` and\n passing them on to `_resource_apply_sparse`. Optimizers which deal correctly\n with duplicate indices may instead override this method to avoid the\n overhead of summing.\n\n Args:\n grad: a `Tensor` representing the gradient for the affected indices.\n handle: a `Tensor` of dtype `resource` which points to the variable\n to be updated.\n indices: a `Tensor` of integral type representing the indices for\n which the gradient is nonzero. Indices may be repeated.\n\n Returns:\n An `Operation` which updates the value of the variable.\n \"\"\"\n summed_grad, unique_indices = _deduplicate_indexed_slices(\n values=grad, indices=indices)\n return self._resource_apply_sparse(summed_grad, handle, unique_indices)\n\n def _resource_apply_sparse(self, grad, handle, indices):\n \"\"\"Add ops to apply sparse gradients to the variable `handle`.\n\n Similar to `_apply_sparse`, the `indices` argument to this method has been\n de-duplicated. Optimizers which deal correctly with non-unique indices may\n instead override `_resource_apply_sparse_duplicate_indices` to avoid this\n overhead.\n\n Args:\n grad: a `Tensor` representing the gradient for the affected indices.\n handle: a `Tensor` of dtype `resource` which points to the variable\n to be updated.\n indices: a `Tensor` of integral type representing the indices for\n which the gradient is nonzero. Indices are unique.\n\n Returns:\n An `Operation` which updates the value of the variable.\n \"\"\"\n raise NotImplementedError()\n\n def _apply_sparse_duplicate_indices(self, grad, var):\n \"\"\"Add ops to apply sparse gradients to `var`, with repeated sparse indices.\n\n Optimizers which override this method must deal with IndexedSlices objects\n such as the following:\n\n IndexedSlicesValue(values=[1, 1], indices=[0, 0], dense_shape=[1])\n\n The correct interpretation is:\n\n IndexedSlicesValue(values=[2], indices=[0], dense_shape=[1])\n\n Many optimizers deal incorrectly with repeated indices when updating based\n on sparse gradients (e.g. summing squares rather than squaring the sum, or\n applying momentum terms multiple times). Adding first is always the correct\n behavior, so this is enforced here by reconstructing the IndexedSlices to\n have only unique indices, then calling _apply_sparse.\n\n Optimizers which deal correctly with repeated indices may instead override\n this method to avoid the overhead of summing indices.\n\n Args:\n grad: `IndexedSlices`.\n var: A `Variable` object.\n\n Returns:\n An `Operation`.\n \"\"\"\n summed_values, unique_indices = _deduplicate_indexed_slices(\n values=grad.values, indices=grad.indices)\n gradient_no_duplicate_indices = ops.IndexedSlices(\n indices=unique_indices,\n values=summed_values,\n dense_shape=grad.dense_shape)\n return self._apply_sparse(gradient_no_duplicate_indices, var)\n\n def _apply_sparse(self, grad, var):\n \"\"\"Add ops to apply sparse gradients to `var`.\n\n The IndexedSlices object passed to `grad` in this function is by default\n pre-processed in `_apply_sparse_duplicate_indices` to remove duplicate\n indices (see its docstring for details). Optimizers which can tolerate or\n have correct special cases for duplicate sparse indices may override\n `_apply_sparse_duplicate_indices` instead of this function, avoiding that\n overhead.\n\n Args:\n grad: `IndexedSlices`, with no repeated indices.\n var: A `Variable` object.\n\n Returns:\n An `Operation`.\n \"\"\"\n raise NotImplementedError()\n\n def _finish(self, update_ops, name_scope):\n \"\"\"Do what is needed to finish the update.\n\n This is called with the `name_scope` using the \"name\" that\n users have chosen for the application of gradients.\n\n Args:\n update_ops: List of `Operation` objects to update variables. This list\n contains the values returned by the `_apply_dense()` and\n `_apply_sparse()` calls.\n name_scope: String. Name to use for the returned operation.\n\n Returns:\n The operation to apply updates.\n \"\"\"\n return control_flow_ops.group(*update_ops, name=name_scope)\n\n # --------------\n # Utility methods for subclasses.\n # --------------\n\n def _slot_dict(self, slot_name):\n \"\"\"Returns a dict for caching slots created under the given name.\n\n Args:\n slot_name: Name for the slot.\n\n Returns:\n A dict that maps primary `Variable` objects to the slot created\n for that variable, under the given slot name.\n \"\"\"\n named_slots = self._slots.get(slot_name, None)\n if named_slots is None:\n named_slots = {}\n self._slots[slot_name] = named_slots\n return named_slots\n\n def _get_or_make_slot(self, var, val, slot_name, op_name):\n \"\"\"Find or create a slot for a variable.\n\n Args:\n var: A `Variable` object.\n val: A `Tensor`. The initial value of the slot.\n slot_name: Name for the slot.\n op_name: Name to use when scoping the Variable that\n needs to be created for the slot.\n\n Returns:\n A `Variable` object.\n \"\"\"\n named_slots = self._slot_dict(slot_name)\n if _var_key(var) not in named_slots:\n new_slot_variable = slot_creator.create_slot(var, val, op_name)\n self._restore_slot_variable(\n slot_name=slot_name, variable=var,\n slot_variable=new_slot_variable)\n named_slots[_var_key(var)] = new_slot_variable\n return named_slots[_var_key(var)]\n\n def _get_or_make_slot_with_initializer(self, var, initializer, shape, dtype,\n slot_name, op_name):\n \"\"\"Find or create a slot for a variable, using an Initializer.\n\n Args:\n var: A `Variable` object.\n initializer: An `Initializer`. The initial value of the slot.\n shape: Shape of the initial value of the slot.\n dtype: Type of the value of the slot.\n slot_name: Name for the slot.\n op_name: Name to use when scoping the Variable that\n needs to be created for the slot.\n\n Returns:\n A `Variable` object.\n \"\"\"\n named_slots = self._slot_dict(slot_name)\n if _var_key(var) not in named_slots:\n new_slot_variable = slot_creator.create_slot_with_initializer(\n var, initializer, shape, dtype, op_name)\n self._restore_slot_variable(\n slot_name=slot_name, variable=var,\n slot_variable=new_slot_variable)\n named_slots[_var_key(var)] = new_slot_variable\n return named_slots[_var_key(var)]\n\n def _zeros_slot(self, var, slot_name, op_name):\n \"\"\"Find or create a slot initialized with 0.0.\n\n Args:\n var: A `Variable` object.\n slot_name: Name for the slot.\n op_name: Name to use when scoping the Variable that\n needs to be created for the slot.\n\n Returns:\n A `Variable` object.\n \"\"\"\n named_slots = self._slot_dict(slot_name)\n if _var_key(var) not in named_slots:\n new_slot_variable = slot_creator.create_zeros_slot(var, op_name)\n self._restore_slot_variable(\n slot_name=slot_name, variable=var,\n slot_variable=new_slot_variable)\n named_slots[_var_key(var)] = new_slot_variable\n return named_slots[_var_key(var)]\n\n # --------------\n # For implementing the Checkpointable interface.\n # --------------\n\n def _restore_slot_variable(self, slot_name, variable, slot_variable):\n \"\"\"Restore a newly created slot variable's value.\"\"\"\n variable_key = _var_key(variable)\n deferred_restorations = self._deferred_slot_restorations.get(\n slot_name, {}).pop(variable_key, [])\n # Iterate over restores, highest restore UID first to minimize the number\n # of assignments.\n deferred_restorations.sort(key=lambda position: position.restore_uid,\n reverse=True)\n for checkpoint_position in deferred_restorations:\n checkpoint_position.restore(slot_variable)\n\n def _create_or_restore_slot_variable(\n self, slot_variable_position, slot_name, variable):\n \"\"\"Restore a slot variable's value, possibly creating it.\n\n Called when a variable which has an associated slot variable is created or\n restored. When executing eagerly, we create the slot variable with a\n restoring initializer.\n\n No new variables are created when graph building. Instead,\n _restore_slot_variable catches these after normal creation and adds restore\n ops to the graph. This method is nonetheless important when graph building\n for the case when a slot variable has already been created but `variable`\n has just been added to a dependency graph (causing us to realize that the\n slot variable needs to be restored).\n\n Args:\n slot_variable_position: A `checkpointable._CheckpointPosition` object\n indicating the slot variable `Checkpointable` object to be restored.\n slot_name: The name of this `Optimizer`'s slot to restore into.\n variable: The variable object this slot is being created for.\n \"\"\"\n named_slots = self._slot_dict(slot_name)\n variable_key = _var_key(variable)\n slot_variable = named_slots.get(variable_key, None)\n if (slot_variable is None and context.executing_eagerly() and\n slot_variable_position.is_simple_variable()\n # Defer slot variable creation if there is an active variable creator\n # scope. Generally we'd like to eagerly create/restore slot variables\n # when possible, but this may mean that scopes intended to catch\n # `variable` also catch its eagerly created slot variable\n # unintentionally (specifically make_template would add a dependency on\n # a slot variable if not for this case). Deferring is mostly harmless\n # (aside from double initialization), and makes variable creator scopes\n # behave the same way they do when graph building.\n and not ops.get_default_graph()._variable_creator_stack): # pylint: disable=protected-access\n initializer = checkpointable.CheckpointInitialValue(\n checkpoint_position=slot_variable_position)\n slot_variable = self._get_or_make_slot(\n var=variable,\n val=initializer,\n slot_name=slot_name,\n op_name=self._name)\n # Slot variables are not owned by any one object (because we don't want to\n # save the slot variable if the optimizer is saved without the non-slot\n # variable, or if the non-slot variable is saved without the optimizer;\n # it's a dependency hypergraph with edges of the form (optimizer, non-slot\n # variable, variable)). So we don't _track_ slot variables anywhere, and\n # instead special-case this dependency and otherwise pretend it's a normal\n # graph.\n if slot_variable is not None:\n # If we've either made this slot variable, or if we've pulled out an\n # existing slot variable, we should restore it.\n slot_variable_position.restore(slot_variable)\n else:\n # We didn't make the slot variable. Defer restoring until it gets created\n # normally. We keep a list rather than the one with the highest restore\n # UID in case slot variables have their own dependencies, in which case\n # those could differ between restores.\n self._deferred_slot_restorations.setdefault(\n slot_name, {}).setdefault(variable_key, []).append(\n slot_variable_position)\n\n def _call_if_callable(self, param):\n \"\"\"Call the function if param is callable.\"\"\"\n return param() if callable(param) else param\n"
] | [
[
"tensorflow.python.ops.variable_scope.variable",
"tensorflow.python.framework.ops.colocate_with",
"tensorflow.python.framework.ops.convert_to_tensor_or_indexed_slices",
"tensorflow.python.training.checkpointable.base.CheckpointableReference",
"tensorflow.python.util.nest.flatten",
"tensorflow.python.ops.control_flow_ops.tuple",
"tensorflow.python.training.checkpointable.base.CheckpointInitialValue",
"tensorflow.python.training.distribute.has_distribution_strategy",
"tensorflow.python.training.slot_creator.create_zeros_slot",
"tensorflow.python.framework.ops.IndexedSlices",
"tensorflow.python.util.tf_export.tf_export",
"tensorflow.python.eager.backprop.GradientTape",
"tensorflow.python.training.distribute.get_distribution_strategy",
"tensorflow.python.ops.state_ops.assign_add",
"tensorflow.python.ops.control_flow_ops.group",
"tensorflow.python.ops.gradients.gradients",
"tensorflow.python.ops.array_ops.unique",
"tensorflow.python.ops.array_ops.shape",
"tensorflow.python.training.slot_creator.create_slot_with_initializer",
"tensorflow.python.ops.variables.trainable_variables",
"tensorflow.python.framework.ops.control_dependencies",
"tensorflow.python.training.distribute.get_loss_reduction",
"tensorflow.python.framework.ops.init_scope",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.framework.ops.get_default_graph",
"tensorflow.python.training.slot_creator.create_slot",
"tensorflow.python.training.distribute.get_tower_context",
"tensorflow.python.framework.ops.get_collection",
"tensorflow.python.framework.ops.name_scope",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.training.distribute.get_cross_tower_context",
"tensorflow.python.framework.ops.get_collection_ref"
]
] |
sayandipdutta/sphereface_pytorch | [
"762c458f9258a8d85210a92c2ae0548942e4e062"
] | [
"train.py"
] | [
"from __future__ import print_function\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\ntorch.backends.cudnn.bencmark = True\n\nimport os,sys,cv2,random,datetime\nimport argparse\nimport numpy as np\n\nfrom dataset import ImageDataset\nfrom matlab_cp2tform import get_similarity_transform_for_cv2\nimport net_sphere\n\n\nparser = argparse.ArgumentParser(description='PyTorch sphereface')\nparser.add_argument('--net','-n', default='sphere20a', type=str)\nparser.add_argument('--dataset', default='../../dataset/face/casia/casia.zip', type=str)\nparser.add_argument('--lr', default=0.1, type=float, help='learning rate')\nparser.add_argument('--bs', default=256, type=int, help='')\nargs = parser.parse_args()\nuse_cuda = torch.cuda.is_available()\n\n\ndef alignment(src_img,src_pts):\n of = 2\n ref_pts = [ [30.2946+of, 51.6963+of],[65.5318+of, 51.5014+of],\n [48.0252+of, 71.7366+of],[33.5493+of, 92.3655+of],[62.7299+of, 92.2041+of] ]\n crop_size = (96+of*2, 112+of*2)\n\n s = np.array(src_pts).astype(np.float32)\n r = np.array(ref_pts).astype(np.float32)\n\n tfm = get_similarity_transform_for_cv2(s, r)\n face_img = cv2.warpAffine(src_img, tfm, crop_size)\n return face_img\n\n\ndef dataset_load(name,filename,pindex,cacheobj,zfile):\n position = filename.rfind('.zip:')\n zipfilename = filename[0:position+4]\n nameinzip = filename[position+5:]\n\n split = nameinzip.split('\\t')\n nameinzip = split[0]\n classid = int(split[1])\n src_pts = []\n for i in range(5):\n src_pts.append([int(split[2*i+2]),int(split[2*i+3])])\n\n data = np.frombuffer(zfile.read(nameinzip),np.uint8)\n img = cv2.imdecode(data,1)\n img = alignment(img,src_pts)\n\n if ':train' in name:\n if random.random()>0.5: img = cv2.flip(img,1)\n if random.random()>0.5:\n rx = random.randint(0,2*2)\n ry = random.randint(0,2*2)\n img = img[ry:ry+112,rx:rx+96,:]\n else:\n img = img[2:2+112,2:2+96,:]\n else:\n img = img[2:2+112,2:2+96,:]\n\n\n img = img.transpose(2, 0, 1).reshape((1,3,112,96))\n img = ( img - 127.5 ) / 128.0\n label = np.zeros((1,1),np.float32)\n label[0,0] = classid\n return (img,label)\n\n\ndef printoneline(*argv):\n s = ''\n for arg in argv: s += str(arg) + ' '\n s = s[:-1]\n sys.stdout.write('\\r'+s)\n sys.stdout.flush()\n\ndef save_model(model,filename):\n state = model.state_dict()\n for key in state: state[key] = state[key].clone().cpu()\n torch.save(state, filename)\n\ndef dt():\n return datetime.datetime.now().strftime('%H:%M:%S')\n\n\n\ndef train(epoch,args):\n net.train()\n train_loss = 0\n correct = 0\n total = 0\n batch_idx = 0\n ds = ImageDataset(args.dataset,dataset_load,'data/casia_landmark.txt',name=args.net+':train',\n bs=args.bs,shuffle=True,nthread=6,imagesize=128)\n while True:\n img,label = ds.get()\n if img is None: break\n inputs = torch.from_numpy(img).float()\n targets = torch.from_numpy(label[:,0]).long()\n if use_cuda: inputs, targets = inputs.cuda(), targets.cuda()\n\n optimizer.zero_grad()\n inputs, targets = Variable(inputs), Variable(targets)\n outputs = net(inputs)\n loss = criterion(outputs, targets)\n lossd = loss.data[0]\n loss.backward()\n optimizer.step()\n\n train_loss += loss.data[0]\n outputs = outputs[0] # 0=cos_theta 1=phi_theta\n _, predicted = torch.max(outputs.data, 1)\n total += targets.size(0)\n correct += predicted.eq(targets.data).cpu().sum()\n\n printoneline(dt(),'Te=%d Loss=%.4f | AccT=%.4f%% (%d/%d) %.4f %.2f %d'\n % (epoch,train_loss/(batch_idx+1), 100.0*correct/total, correct, total, \n lossd, criterion.lamb, criterion.it))\n batch_idx += 1\n print('')\n\n\nnet = getattr(net_sphere,args.net)()\n# net.load_state_dict(torch.load('sphere20a_0.pth'))\nnet.cuda()\ncriterion = net_sphere.AngleLoss()\n\n\nprint('start: time={}'.format(dt()))\nfor epoch in range(0, 20):\n if epoch in [0,10,15,18]:\n if epoch!=0: args.lr *= 0.1\n optimizer = optim.SGD(net.parameters(), lr=args.lr, momentum=0.9, weight_decay=5e-4)\n\n train(epoch,args)\n save_model(net, '{}_{}.pth'.format(args.net,epoch))\n\nprint('finish: time={}\\n'.format(dt()))\n\n"
] | [
[
"numpy.zeros",
"torch.save",
"torch.autograd.Variable",
"torch.cuda.is_available",
"torch.from_numpy",
"torch.max",
"numpy.array"
]
] |
toolkmit/algotrading | [
"693f84b67d1b5bf07450f37295053f32550ac9cf"
] | [
"training/gpu_util_sampler.py"
] | [
"import gpustat\nimport numpy as np\nfrom keras.callbacks import Callback\n\n\nclass GPUUtilizationSampler(Callback):\n \"\"\"\n Measure GPU utilization at the end of 1% of all batches.\n (The more frequent the measuring, the slower and less accurate this callback becomes.)\n If GPU is not present, report 0 utilization.\n \"\"\"\n def __init__(self, gpu_ind):\n self.gpu_ind = gpu_ind\n super()\n\n def on_train_begin(self, logs={}):\n self.samples = []\n\n def on_batch_end(self, batch, logs={}):\n if np.random.rand() > 0.99:\n try:\n gpu_info = gpustat.GPUStatCollection.new_query()[self.gpu_ind]\n self.samples.append(gpu_info.utilization)\n except Exception:\n self.samples.append(0)"
] | [
[
"numpy.random.rand"
]
] |
zczllw5/wclient | [
"d03943b7060150662123b8a7d3918f08fcfac25d"
] | [
"data_process/data_process_txt_to_csv.py"
] | [
"import csv\nimport pandas as pd\n\nwith open(\"1_3_connected.txt\") as fin, open(\"1_3_connected.csv\", 'w') as fout:\n o=csv.writer(fout)\n for line in fin:\n o.writerow(line.split())\n\ndf = pd.read_csv('1_3_connected.csv')\ndf1 = df.T\ndf1.to_csv('1_3_connected_output.csv')"
] | [
[
"pandas.read_csv"
]
] |
rlagywjd802/gym-sawyer | [
"385bbeafcccb61afb9099554f6a99b16f1f1a7c5"
] | [
"sawyer/garage/misc/logger.py"
] | [
"import base64\nfrom contextlib import contextmanager\nimport csv\nimport datetime\nfrom enum import Enum\nimport json\nimport os\nimport os.path as osp\nimport pickle\nimport sys\nimport types\n\nimport dateutil.tz\nimport joblib\nimport numpy as np\n\nfrom sawyer.garage.misc.autoargs import get_all_parameters\nfrom sawyer.garage.misc.console import colorize, mkdir_p\nfrom sawyer.garage.misc.tabulate import tabulate\nfrom sawyer.garage.misc.tensorboard_output import TensorBoardOutput\n\n_prefixes = []\n_prefix_str = ''\n\n_tabular_prefixes = []\n_tabular_prefix_str = ''\n\n_tabular = []\n\n_text_outputs = []\n_tabular_outputs = []\n\n_text_fds = {}\n_tabular_fds = {}\n_tabular_header_written = set()\n\n_snapshot_dir = None\n_snapshot_mode = 'all'\n_snapshot_gap = 1\n\n_log_tabular_only = False\n_header_printed = False\n\n_tensorboard_step_key = None\n\n_tensorboard = TensorBoardOutput()\n\n\ndef _add_output(file_name, arr, fds, mode='a'):\n if file_name not in arr:\n mkdir_p(os.path.dirname(file_name))\n arr.append(file_name)\n fds[file_name] = open(file_name, mode)\n\n\ndef _remove_output(file_name, arr, fds):\n if file_name in arr:\n fds[file_name].close()\n del fds[file_name]\n arr.remove(file_name)\n\n\ndef push_prefix(prefix):\n _prefixes.append(prefix)\n global _prefix_str\n _prefix_str = ''.join(_prefixes)\n\n\ndef add_text_output(file_name):\n _add_output(file_name, _text_outputs, _text_fds, mode='a')\n\n\ndef remove_text_output(file_name):\n _remove_output(file_name, _text_outputs, _text_fds)\n\n\ndef add_tabular_output(file_name):\n _add_output(file_name, _tabular_outputs, _tabular_fds, mode='w')\n\n\ndef remove_tabular_output(file_name):\n if _tabular_fds[file_name] in _tabular_header_written:\n _tabular_header_written.remove(_tabular_fds[file_name])\n _remove_output(file_name, _tabular_outputs, _tabular_fds)\n\n\ndef set_tensorboard_dir(dir_name):\n _tensorboard.set_dir(dir_name)\n log(\"tensorboard data will be logged into:\" + dir_name)\n\n\ndef set_snapshot_dir(dir_name):\n global _snapshot_dir\n _snapshot_dir = dir_name\n\n\ndef get_snapshot_dir():\n return _snapshot_dir\n\n\ndef get_snapshot_mode():\n return _snapshot_mode\n\n\ndef set_snapshot_mode(mode):\n global _snapshot_mode\n _snapshot_mode = mode\n\n\ndef get_snapshot_gap():\n return _snapshot_gap\n\n\ndef set_snapshot_gap(gap):\n global _snapshot_gap\n _snapshot_gap = gap\n\n\ndef set_log_tabular_only(log_tabular_only):\n global _log_tabular_only\n _log_tabular_only = log_tabular_only\n\n\ndef set_tensorboard_step_key(key):\n global _tensorboard_step_key\n _tensorboard_step_key = key\n\n\ndef get_log_tabular_only():\n return _log_tabular_only\n\n\ndef log(s, with_prefix=True, with_timestamp=True, color=None):\n out = s\n if with_prefix:\n out = _prefix_str + out\n # out_basic holds output with a simpler timestamp for stdout\n out_basic = out\n if with_timestamp:\n now = datetime.datetime.now(dateutil.tz.tzlocal())\n timestamp_basic = now.strftime('%Y-%m-%d %H:%M:%S')\n timestamp = now.strftime('%Y-%m-%d %H:%M:%S.%f %Z')\n out_basic = \"%s | %s\" % (timestamp_basic, out_basic)\n out = \"%s | %s\" % (timestamp, out)\n if color is not None:\n out = colorize(out, color)\n out_basic = colorize(out_basic, color)\n if not _log_tabular_only:\n # Also log to stdout\n print(out_basic)\n for fd in list(_text_fds.values()):\n fd.write(out + '\\n')\n fd.flush()\n sys.stdout.flush()\n\n\ndef record_tabular(key, val):\n _tensorboard.record_scalar(str(key), val)\n _tabular.append((_tabular_prefix_str + str(key), str(val)))\n\n\ndef record_tensor(key, val):\n \"\"\"Record tf.Tensor into tensorboard with Tensor.name and its value.\"\"\"\n _tensorboard.record_tensor(key, val)\n\n\ndef record_histogram(key, val):\n _tensorboard.record_histogram(str(key), val)\n\n\ndef record_histogram_by_type(histogram_type, key=None, shape=[1000], **kwargs):\n _tensorboard.record_histogram_by_type(histogram_type, key, shape, **kwargs)\n\n\ndef push_tabular_prefix(key):\n _tabular_prefixes.append(key)\n global _tabular_prefix_str\n _tabular_prefix_str = ''.join(_tabular_prefixes)\n\n\ndef pop_tabular_prefix():\n del _tabular_prefixes[-1]\n global _tabular_prefix_str\n _tabular_prefix_str = ''.join(_tabular_prefixes)\n\n\n@contextmanager\ndef prefix(key):\n push_prefix(key)\n try:\n yield\n finally:\n pop_prefix()\n\n\n@contextmanager\ndef tabular_prefix(key):\n push_tabular_prefix(key)\n yield\n pop_tabular_prefix()\n\n\nclass TerminalTablePrinter:\n def __init__(self):\n self.headers = None\n self.tabulars = []\n\n def print_tabular(self, new_tabular):\n if self.headers is None:\n self.headers = [x[0] for x in new_tabular]\n else:\n assert len(self.headers) == len(new_tabular)\n self.tabulars.append([x[1] for x in new_tabular])\n self.refresh()\n\n def refresh(self):\n import os\n rows, columns = os.popen('stty size', 'r').read().split()\n tabulars = self.tabulars[-(int(rows) - 3):]\n sys.stdout.write(\"\\x1b[2J\\x1b[H\")\n sys.stdout.write(tabulate(tabulars, self.headers))\n sys.stdout.write(\"\\n\")\n\n\ntable_printer = TerminalTablePrinter()\n\n\ndef dump_tensorboard(*args, **kwargs):\n if _tabular:\n tabular_dict = dict(_tabular)\n step = None\n if _tensorboard_step_key and _tensorboard_step_key in tabular_dict:\n step = tabular_dict[_tensorboard_step_key]\n _tensorboard.dump_tensorboard(step)\n\n\ndef dump_tabular(*args, **kwargs):\n wh = kwargs.pop(\"write_header\", None)\n if _tabular:\n if _log_tabular_only:\n table_printer.print_tabular(_tabular)\n else:\n for line in tabulate(_tabular).split('\\n'):\n log(line, *args, **kwargs)\n tabular_dict = dict(_tabular)\n\n # Also write to the csv files\n # This assumes that the keys in each iteration won't change!\n for tabular_fd in list(_tabular_fds.values()):\n writer = csv.DictWriter(\n tabular_fd, fieldnames=list(tabular_dict.keys()))\n if wh or (wh is None\n and tabular_fd not in _tabular_header_written):\n writer.writeheader()\n _tabular_header_written.add(tabular_fd)\n writer.writerow(tabular_dict)\n tabular_fd.flush()\n del _tabular[:]\n\n # write to the tensorboard folder\n # This assumes that the keys in each iteration won't change!\n dump_tensorboard(args, kwargs)\n\n\ndef pop_prefix():\n del _prefixes[-1]\n global _prefix_str\n _prefix_str = ''.join(_prefixes)\n\n\ndef save_itr_params(itr, params):\n if _snapshot_dir:\n if _snapshot_mode == 'all':\n file_name = osp.join(_snapshot_dir, 'itr_%d.pkl' % itr)\n joblib.dump(params, file_name, compress=3)\n elif _snapshot_mode == 'last':\n # override previous params\n file_name = osp.join(_snapshot_dir, 'params.pkl')\n joblib.dump(params, file_name, compress=3)\n elif _snapshot_mode == \"gap\":\n if itr % _snapshot_gap == 0:\n file_name = osp.join(_snapshot_dir, 'itr_%d.pkl' % itr)\n joblib.dump(params, file_name, compress=3)\n elif _snapshot_mode == 'none':\n pass\n else:\n raise NotImplementedError\n\n\ndef log_parameters(log_file, args, classes):\n log_params = {}\n for param_name, param_value in args.__dict__.items():\n if any([param_name.startswith(x) for x in list(classes.keys())]):\n continue\n log_params[param_name] = param_value\n for name, cls in classes.items():\n if isinstance(cls, type):\n params = get_all_parameters(cls, args)\n params[\"_name\"] = getattr(args, name)\n log_params[name] = params\n else:\n log_params[name] = getattr(cls, \"__kwargs\", dict())\n log_params[name][\n \"_name\"] = cls.__module__ + \".\" + cls.__class__.__name__\n mkdir_p(os.path.dirname(log_file))\n with open(log_file, \"w\") as f:\n json.dump(log_params, f, indent=2, sort_keys=True)\n\n\ndef stub_to_json(stub_sth):\n from sawyer.garage.misc import instrument\n if isinstance(stub_sth, instrument.StubObject):\n assert not stub_sth.args\n data = dict()\n for k, v in stub_sth.kwargs.items():\n data[k] = stub_to_json(v)\n data[\"_name\"] = stub_sth.proxy_class.__module__ + \\\n \".\" + stub_sth.proxy_class.__name__\n return data\n elif isinstance(stub_sth, instrument.StubAttr):\n return dict(\n obj=stub_to_json(stub_sth.obj),\n attr=stub_to_json(stub_sth.attr_name))\n elif isinstance(stub_sth, instrument.StubMethodCall):\n return dict(\n obj=stub_to_json(stub_sth.obj),\n method_name=stub_to_json(stub_sth.method_name),\n args=stub_to_json(stub_sth.args),\n kwargs=stub_to_json(stub_sth.kwargs),\n )\n elif isinstance(stub_sth, instrument.BinaryOp):\n return \"binary_op\"\n elif isinstance(stub_sth, instrument.StubClass):\n return stub_sth.proxy_class.__module__ + \".\" + \\\n stub_sth.proxy_class.__name__\n elif isinstance(stub_sth, dict):\n return {stub_to_json(k): stub_to_json(v) for k, v in stub_sth.items()}\n elif isinstance(stub_sth, (list, tuple)):\n return list(map(stub_to_json, stub_sth))\n elif isinstance(stub_sth, types.LambdaType):\n if stub_sth.__module__ is not None:\n return stub_sth.__module__ + \".\" + stub_sth.__name__\n return stub_sth.__name__\n elif \"theano\" in str(type(stub_sth)):\n return repr(stub_sth)\n return stub_sth\n\n\nclass MyEncoder(json.JSONEncoder):\n def default(self, o):\n if isinstance(o, type):\n return {'$class': o.__module__ + \".\" + o.__name__}\n elif isinstance(o, Enum):\n return {\n '$enum':\n o.__module__ + \".\" + o.__class__.__name__ + '.' + o.name\n }\n return json.JSONEncoder.default(self, o)\n\n\ndef log_parameters_lite(log_file, args):\n log_params = {}\n for param_name, param_value in args.__dict__.items():\n log_params[param_name] = param_value\n if args.args_data is not None:\n stub_method = pickle.loads(base64.b64decode(args.args_data))\n method_args = stub_method.kwargs\n log_params[\"json_args\"] = dict()\n for k, v in list(method_args.items()):\n log_params[\"json_args\"][k] = stub_to_json(v)\n kwargs = stub_method.obj.kwargs\n for k in [\"baseline\", \"env\", \"policy\"]:\n if k in kwargs:\n log_params[\"json_args\"][k] = stub_to_json(kwargs.pop(k))\n log_params[\"json_args\"][\"algo\"] = stub_to_json(stub_method.obj)\n mkdir_p(os.path.dirname(log_file))\n with open(log_file, \"w\") as f:\n json.dump(log_params, f, indent=2, sort_keys=True, cls=MyEncoder)\n\n\ndef log_variant(log_file, variant_data):\n mkdir_p(os.path.dirname(log_file))\n if hasattr(variant_data, \"dump\"):\n variant_data = variant_data.dump()\n variant_json = stub_to_json(variant_data)\n with open(log_file, \"w\") as f:\n json.dump(variant_json, f, indent=2, sort_keys=True, cls=MyEncoder)\n\n\ndef record_tabular_misc_stat(key, values, placement='back'):\n if placement == 'front':\n prefix = \"\"\n suffix = key\n else:\n prefix = key\n suffix = \"\"\n if values:\n record_tabular(prefix + \"Average\" + suffix, np.average(values))\n record_tabular(prefix + \"Std\" + suffix, np.std(values))\n record_tabular(prefix + \"Median\" + suffix, np.median(values))\n record_tabular(prefix + \"Min\" + suffix, np.min(values))\n record_tabular(prefix + \"Max\" + suffix, np.max(values))\n else:\n record_tabular(prefix + \"Average\" + suffix, np.nan)\n record_tabular(prefix + \"Std\" + suffix, np.nan)\n record_tabular(prefix + \"Median\" + suffix, np.nan)\n record_tabular(prefix + \"Min\" + suffix, np.nan)\n record_tabular(prefix + \"Max\" + suffix, np.nan)\n"
] | [
[
"numpy.median",
"numpy.max",
"numpy.min",
"numpy.std",
"numpy.average"
]
] |
Seny-l/metaMIC | [
"eef5f151c49b1a306d143e3c524ea4bb90ad2efb"
] | [
"metaMIC/metaMIC.py"
] | [
"#!/usr/bin/env python\n\nimport pandas as pd\nimport numpy as np\nimport multiprocessing\nfrom optparse import OptionParser\nimport argparse\nimport operator\nimport os\nimport random\nimport sys\nimport time\nimport random\nimport subprocess\nimport pysam\nimport collections\nimport re\nimport math\nfrom Bio import SeqIO\nimport joblib\nimport warnings\nfrom sklearn.ensemble import IsolationForest\nfrom scipy import stats\nimport logging\nimport hashlib\nimport requests\nimport shutil\nimport tarfile\nimport gzip\nfrom .extract import extract_features\n\nbase_path = os.path.split(__file__)[0]\ncontig_features = [\n 'coverage_width',\n 'deviation_width',\n 'normalized_deviation',\n 'window_cov_dev',\n 'fragment_width',\n 'fragment_deviation_width',\n 'normalized_fragment_deviation',\n 'window_frag_cov_dev',\n 'proper_read_ratio',\n 'clipped_read_ratio',\n 'supplementary_read_ratio',\n 'inversion_read_ratio',\n 'discordant_loc_ratio',\n 'discordant_size_ratio',\n 'read_breakpoint_ratio',\n 'proper_read_width',\n 'clipped_read_width',\n 'supplementary_read_width',\n 'inversion_read_width',\n 'discordant_loc_width',\n 'discordant_size_width',\n 'read_breakpoint_max',\n 'disagree_width',\n 'correct_portion',\n 'ambiguous_portion',\n 'insert_portion',\n 'deletion_portion',\n 'disagree_portion',\n 'mean_KAD',\n 'abnormal_KAD_ratio',\n 'dev_KAD',\n 'KAD_width',\n 'coverage_diff',\n 'length']\nwindow_features = [\n 'correct_portion',\n 'ambiguous_portion',\n 'disagree_portion',\n 'deletion_portion',\n 'insert_portion',\n 'mean_KAD',\n 'abnormal_KAD_ratio',\n 'dev_KAD',\n 'normalized_fragment_coverage',\n 'normalized_fragment_deviation',\n 'normalized_coverage',\n 'normalized_deviation',\n 'mean_coverage',\n 'coverage_diff',\n 'read_breakpoint_ratio',\n 'proper_read_ratio',\n 'inversion_read_ratio',\n 'clipped_read_ratio',\n 'supplementary_read_ratio',\n 'discordant_loc_ratio',\n 'discordant_size_ratio']\n\n\ndef get_opts(args):\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n description=' Reference-free Misassembly Identification and Correction of metagenomic assemblies')\n\n subparsers = parser.add_subparsers(title='metaMIC subcommands',\n dest='cmd',\n metavar='')\n\n download_model = subparsers.add_parser('download_model',\n help='download model')\n\n extract_feature = subparsers.add_parser('extract_feature',\n help='Extract features from inputs.')\n\n extract_feature.add_argument(\n \"-t\",\n \"--threads\",\n dest=\"threads\",\n required=False,\n type=int,\n default=8,\n help='Maximum number of threads [default: 8]')\n\n extract_feature.add_argument(\n \"--bam\",\n dest=\"bamfile\",\n required=False,\n help=\"index bam file for alignment\")\n\n extract_feature.add_argument(\n \"--r1\",\n dest=\"read1\",\n required=False,\n help=\"read1\")\n\n extract_feature.add_argument(\n \"--r2\",\n dest=\"read2\",\n required=False,\n help=\"read2\")\n\n extract_feature.add_argument(\n \"-p\",\n \"--r\",\n dest=\"read\",\n help=\"smart pairing (ignoring #2 fasta/q)\")\n\n extract_feature.add_argument(\n \"-c\",\n \"--contig\",\n dest=\"assemblies\",\n required=True,\n help=\"fasta file of assembled contigs\")\n\n extract_feature.add_argument(\n \"-o\",\n \"--output\",\n dest=\"output\",\n required=True,\n help='output directory for AIM results')\n\n extract_feature.add_argument(\n \"--pileup\",\n dest=\"pileup\",\n default='pileup',\n required=True,\n help=\"path to pileup file [samtools mpileup]\")\n\n extract_feature.add_argument(\n \"-m\",\n \"--mode\",\n dest=\"mode\",\n required=True,\n default='meta',\n help=\"Applied to single genomic/metagenomic assemblies [meta/single]\")\n\n extract_feature.add_argument(\n \"-l\",\n \"--mlen\",\n dest=\"min_length\",\n type=int,\n default=5000,\n required=False,\n help='Minimum contig length [default: 5000bp]')\n\n extract_feature.add_argument(\n \"--samtools\",\n dest=\"samtools\",\n default='samtools',\n required=False,\n help=\"path to samtools\")\n\n extract_feature.add_argument(\n \"--jellyfish\",\n dest=\"jellyfish\",\n required=False,\n default=\"jellyfish\",\n help=\"path to jellyfish\")\n\n\n\n predict = subparsers.add_parser('predict',\n help='Predict.')\n predict.add_argument(\n \"-o\",\n \"--output\",\n dest=\"output\",\n required=True,\n help='output directory for AIM results')\n\n predict.add_argument(\n \"-m\",\n \"--mode\",\n dest=\"mode\",\n required=True,\n default='meta',\n help=\"Applied to single genomic/metagenomic assemblies [meta/single]\")\n\n predict.add_argument(\n \"-c\",\n \"--contig\",\n dest=\"assemblies\",\n required=True,\n help=\"fasta file of assembled contigs\")\n\n predict.add_argument(\n \"-a\",\n \"--assembler\",\n dest=\"assembler\",\n required=False,\n default=\"MEGAHIT\",\n help=\"The assembler-specific model or user-trained model used for assembled fasta file [MEGAHIT/IDBA_UD/[new training model specified by users]]\")\n\n predict.add_argument(\n \"--st\",\n dest=\"score_thred\",\n required=False,\n type=float,\n default=None,\n help=\"Threshold of metaMIC contig score for correcting misassemblies in metagenomics[default:0.8]\"\n )\n\n predict.add_argument(\n \"-l\",\n \"--mlen\",\n dest=\"min_length\",\n type=int,\n required=False,\n default=5000,\n help='Minimum contig length [default: 5000bp]')\n\n predict.add_argument(\n \"-s\",\n \"--slen\",\n dest=\"split_length\",\n type=int,\n required=False,\n default=1000,\n help='Minimum length of splitted fragments [default: 1000bp]')\n\n predict.add_argument(\n \"--nb\",\n dest=\"break_count\",\n type=int,\n required=False,\n default=5,\n help='Threshold of read breakpoint counts for correcting misassemblies in metagenomics')\n\n predict.add_argument(\n \"--rb\",\n dest=\"break_ratio\",\n type=float,\n required=False,\n default=0.1,\n help='Threshold of read breakpoint ratio for correcting misassemblies in metagenomics')\n\n predict.add_argument(\n \"--at\",\n dest=\"anomaly_thred\",\n required=False,\n type=float,\n default=0.9,\n help='Threshold of anomaly score for correcting misassemblies in metagenomics')\n\n\n train = subparsers.add_parser('train',\n help='Train model.')\n\n train.add_argument(\n \"-o\",\n \"--output\",\n dest=\"output\",\n required=True,\n help='output directory for AIM results')\n\n train.add_argument(\n \"--label\",\n dest=\"label\",\n help='Misassembly label of contigs for training assemblies')\n\n train.add_argument(\n \"-a\",\n \"--assembler\",\n dest=\"assembler\",\n default=\"MEGAHIT\",\n help=\"The name of the directory of the trained model.\")\n\n train.add_argument(\n \"-t\",\n \"--threads\",\n dest=\"threads\",\n type=int,\n default=8,\n help='Maximum number of CPUs [default: 8]')\n\n\n\n if not args:\n parser.print_help(sys.stderr)\n sys.exit()\n\n return parser.parse_args(args)\n\ndef get_file_md5(fname):\n \"\"\"\n Calculate Md5 for downloaded file\n \"\"\"\n m = hashlib.md5()\n with open(fname,'rb') as fobj:\n while True:\n data = fobj.read(4096)\n if not data:\n break\n m.update(data)\n\n return m.hexdigest()\n\ndef download_model(path, MD5):\n os.makedirs(os.path.join(base_path, 'model'),exist_ok=True)\n download_path = os.path.join(base_path, 'model',os.path.split(path)[1])\n print(download_path)\n with requests.get(path, stream=True) as r:\n with open(download_path, 'wb') as f:\n shutil.copyfileobj(r.raw, f)\n print('Download finished. Checking MD5...')\n if os.path.exists(os.path.join(base_path, 'model', 'MEGAHIT')):\n shutil.rmtree(os.path.join(base_path, 'model', 'MEGAHIT'))\n\n if os.path.exists(os.path.join(base_path, 'model', 'IDBA_UD')):\n shutil.rmtree(os.path.join(base_path, 'model', 'IDBA_UD'))\n\n if os.path.exists(os.path.join(base_path, 'model', 'metaSPAdes')):\n shutil.rmtree(os.path.join(base_path, 'model', 'metaSPAdes'))\n\n\n if get_file_md5(download_path) == MD5:\n try:\n tar = tarfile.open(download_path, \"r:gz\")\n file_names = tar.getnames()\n for file_name in file_names:\n tar.extract(file_name, os.path.join(base_path, 'model'))\n tar.close()\n except Exception:\n sys.stderr.write(\n f\"Error: cannot unzip the file.\")\n sys.exit(1)\n os.remove(download_path)\n\n model_file = os.listdir(os.path.join(base_path, 'model', os.path.split(path)[1].split('.')[0]))\n for temp_gz in model_file:\n try:\n g_file = gzip.GzipFile(os.path.join(os.path.join(base_path, 'model', os.path.split(path)[1].split('.')[0]),temp_gz))\n open(os.path.join(os.path.join(base_path, 'model', os.path.split(path)[1].split('.')[0]),temp_gz[:-3]), \"wb+\").write(g_file.read())\n g_file.close()\n except Exception:\n sys.stderr.write(\n f\"Error: cannot unzip the file.\")\n sys.exit(1)\n os.remove(os.path.join(os.path.join(base_path, 'model', os.path.split(path)[1].split('.')[0]),temp_gz))\n\n else:\n os.remove(download_path)\n sys.stderr.write(\n f\"Error: MD5 check failed, removing '{download_path}'.\\n\")\n sys.exit(1)\n\ndef download():\n print('Downloading model for MEGAHIT')\n download_model('https://zenodo.org/record/4781819/files/MEGAHIT.tar.gz', 'da9038af3582eea04288775a72003e6b')\n print('Downloading model for IDBA_UD')\n download_model('https://zenodo.org/record/4781819/files/IDBA_UD.tar.gz', '9f6835d3033a177055343ecaa78889bc')\n print('Downloading model for metaSPAdes.')\n download_model('https://zenodo.org/record/5768805/files/metaSPAdes.tar.gz',\n 'md5:0c759a28d0ba3490eeba098395c88586 ')\n\ndef filter_contig(options):\n \"\"\"\n remove assemblies with length smaller than required minimal length\n \"\"\"\n input = SeqIO.parse(options.assemblies, \"fasta\")\n input = (record for record in input if len(record.seq) > 1000)\n os.makedirs(os.path.join(options.output, \"temp/contig\"), exist_ok=True)\n SeqIO.write(input, os.path.join(options.output, \"temp/contig/filtered_contigs.fa\"), \"fasta\")\n options.assemblies = os.path.join(options.output, \"temp/contig/filtered_contigs.fa\")\n return options\n\n\ndef mapping(options):\n \"\"\"\n mapping reads to assemblies\n \"\"\"\n command_line = options.bwa + ' index ' + options.assemblies\n os.system(command_line)\n os.makedirs(os.path.join(options.output, \"temp/sam/\"), exist_ok=True)\n output_bam = os.path.join(options.output, \"temp/sam/contigs.filter.sort.bam\")\n options.bamfile = output_bam\n if options.read is None:\n command_bwa = options.bwa + ' mem -a -t ' + str(options.threads) + ' ' + options.assemblies + ' ' + options.read1 + ' ' + \\\n options.read2 + ' | ' + options.samtools + ' view -h -q 10 -m 50 -F 4 -b | ' + \\\n options.samtools + ' sort > ' + output_bam\n else:\n command_bwa = options.bwa + ' mem -a -p -t ' + str(options.threads) + ' ' + options.assemblies + ' ' + options.read + \\\n ' | ' + options.samtools + ' view -h -q 10 -m 50 -F 4 -b | ' + \\\n options.samtools + ' sort > ' + output_bam\n os.system(command_bwa)\n command_index = options.samtools + ' index ' + output_bam\n os.system(command_index)\n return options\n\n\ndef extract_feature(options):\n \"\"\"\n Extract four types of features from bamfiles and generate contig-based/window-based feature matrix\n \"\"\"\n # check if feature file exists\n status = feature_exist(options)\n if status:\n print(\"feature files exist and will not re-extract features\")\n else:\n extract_features(options)\n # check output features\n check_feature(options)\n # Generate contig-based/window-based matrix\n if options.mode == 'single':\n window_matrix = cal_feature(options)\n else:\n window_matrix, contig_matrix = cal_feature(options)\n\n\ndef cov_thread_cal(data):\n up = np.percentile(np.array(data), 95)\n low = np.percentile(np.array(data), 5)\n return up, low\n\n\ndef contig_fea_generate(data):\n # Generate contig-based feature matrix\n grouped = data.groupby(['contig'])\n mean_data = grouped.mean()\n mean_data = mean_data.loc[:, mean_data.columns != 'start_pos']\n data['count'] = 1\n data['proper_status'] = data['proper_read_ratio'] <= 0.9\n data['clipped_status'] = data['clipped_read_ratio'] >= 0.1\n data['supplementary_status'] = data['supplementary_read_ratio'] >= 0.1\n data['inversion_status'] = data['inversion_read_ratio'] >= 0.1\n data['discordant_loc_status'] = data['discordant_loc_ratio'] >= 0.1\n data['discordant_size_status'] = data['discordant_size_ratio'] >= 0.1\n data['KAD_status'] = data['mean_KAD'] > 0.75\n data['disagree_status'] = data['disagree_portion'] > 0.1\n data['coverage_status'] = (data['normalized_coverage'] > cov_thread_cal(list(data['normalized_coverage']))[0]) + \\\n (data['normalized_coverage'] < cov_thread_cal(list(data['normalized_coverage']))[1])\n data['fragment_status'] = (data['normalized_fragment_coverage'] > cov_thread_cal(list(data['normalized_fragment_coverage']))[0]) + \\\n (data['normalized_fragment_coverage'] < cov_thread_cal(list(data['normalized_fragment_coverage']))[1])\n data['deviation_status'] = data['normalized_deviation'] > cov_thread_cal(list(data['normalized_deviation']))[0]\n data['fragment_deviation_status'] = data['normalized_fragment_deviation'] > cov_thread_cal(\n list(data['normalized_fragment_deviation']))[0]\n grouped = data.groupby(['contig'])\n width_data = pd.concat([grouped['proper_status'].sum() /\n grouped['count'].sum(), grouped['clipped_status'].sum() /\n grouped['count'].sum(), grouped['supplementary_status'].sum() /\n grouped['count'].sum(), grouped['inversion_status'].sum() /\n grouped['count'].sum(), grouped['discordant_loc_status'].sum() /\n grouped['count'].sum(), grouped['discordant_size_status'].sum() /\n grouped['count'].sum(), grouped['KAD_status'].sum() /\n grouped['count'].sum(), grouped['disagree_status'].sum() /\n grouped['count'].sum(), grouped['coverage_status'].sum() /\n grouped['count'].sum(), grouped['fragment_status'].sum() /\n grouped['count'].sum(), grouped['deviation_status'].sum() /\n grouped['count'].sum(), grouped['fragment_deviation_status'].sum() /\n grouped['count'].sum()], axis=1)\n width_data.columns = [\n 'proper_read_width',\n 'clipped_read_width',\n 'supplementary_read_width',\n 'inversion_read_width',\n 'discordant_loc_width',\n 'discordant_size_width',\n 'KAD_width',\n 'disagree_width',\n 'coverage_width',\n 'fragment_width',\n 'deviation_width',\n 'fragment_deviation_width']\n dev_data = pd.concat([pd.DataFrame(np.sqrt(grouped['normalized_coverage'].var())),\n pd.DataFrame(np.sqrt(grouped['normalized_fragment_coverage'].var()))], axis=1)\n dev_data.columns = ['window_cov_dev', 'window_frag_cov_dev']\n break_data = pd.DataFrame(grouped['read_breakpoint_ratio'].max())\n break_data.columns = ['read_breakpoint_max']\n contig_data = pd.concat([mean_data, width_data, dev_data, break_data], axis=1)\n contig_data = contig_data.loc[:, contig_features]\n contig_data = contig_data.fillna(0)\n contig_data = contig_data.replace(np.inf, 0)\n return contig_data\n\n\ndef cal_feature(options):\n read_feature = pd.read_csv(os.path.join(options.output,\n \"temp/read_feature/read_feature.txt\"), sep=\"\\t\", index_col=0)\n read_feature['proper_read_ratio'] = read_feature['proper_read_count'] / read_feature['read_count']\n read_feature['inversion_read_ratio'] = read_feature['inversion_read_count'] / read_feature['proper_read_count']\n read_feature['clipped_read_ratio'] = read_feature['clipped_read_count'] / read_feature['proper_read_count']\n read_feature['supplementary_read_ratio'] = read_feature['supplementary_read_count'] / read_feature['proper_read_count']\n read_feature['discordant_loc_ratio'] = read_feature['discordant_loc_count'] / read_feature['proper_read_count']\n read_feature['discordant_size_ratio'] = read_feature['discordant_size_count'] / read_feature['proper_read_count']\n window_read_data = read_feature.loc[:,['contig',\n 'start_pos',\n 'proper_read_ratio',\n 'inversion_read_ratio',\n 'clipped_read_ratio',\n 'supplementary_read_ratio',\n 'discordant_loc_ratio',\n 'discordant_size_ratio',\n 'length']]\n\n frag_coverage = pd.read_csv(os.path.join(options.output,\n \"temp/coverage/fragment_coverage.txt\"), sep=\"\\t\", index_col=0)\n pileup_feature = pd.read_csv(os.path.join(options.output,\n \"temp/pileup/pileup_feature.txt\"), sep=\"\\t\", index_col=0)\n KAD_feature = pd.read_csv(os.path.join(options.output,\n \"temp/KAD/KAD_window_data.txt\"), sep=\"\\t\", index_col=0)\n breakpoint_data = pd.read_csv(os.path.join(options.output,\n \"temp/read_breakpoint/read_breakpoint_per_window.txt\"), sep=\"\\t\", index_col=0)\n window_data = pd.merge(window_read_data, frag_coverage, on=['contig', 'start_pos'])\n window_data = pd.merge(window_data, pileup_feature, on=['contig', 'start_pos'])\n window_data = pd.merge(window_data, KAD_feature, on=['contig', 'start_pos'])\n window_data = pd.merge(window_data, breakpoint_data, on=['contig', 'start_pos'], how='left')\n window_data = window_data.fillna(0)\n window_data['coverage_diff'] = window_data['normalized_coverage'] - \\\n window_data['normalized_fragment_coverage']\n os.makedirs(os.path.join(options.output, \"feature_matrix\"), exist_ok=True)\n window_data = window_data.loc[window_data['mean_coverage'] > 5, ]\n window_data.to_csv(os.path.join(options.output, \"feature_matrix/window_fea_matrix.txt\"), sep=\"\\t\")\n if options.mode == 'single':\n return window_data\n else:\n contig_data = contig_fea_generate(window_data)\n contig_data.to_csv(os.path.join(options.output,\n \"feature_matrix/contig_fea_matrix.txt\"), sep=\"\\t\")\n return window_data, contig_data\n\n\ndef feature_exist(options):\n status = 1\n\n def check_status(f):\n if not os.path.exists(f):\n nonlocal status\n status = 0\n\n check_status(os.path.join(options.output,\n \"temp/read_feature/read_feature.txt\"))\n check_status(os.path.join(options.output,\n \"temp/coverage/fragment_coverage.txt\"))\n check_status(os.path.join(options.output,\n \"temp/read_breakpoint/read_breakpoint_per_window.txt\"))\n check_status(os.path.join(options.output,\n \"temp/pileup/pileup_feature.txt\"))\n check_status(os.path.join(options.output,\n \"temp/KAD/KAD_window_data.txt\"))\n\n return status\n\n\ndef check_feature(options):\n def check_path(f):\n if not os.path.exists(f):\n sys.stderr.write(f\"Error: Expected file '{f}' does not exist\\n\")\n sys.exit(1)\n check_path(os.path.join(options.output,\n \"temp/read_feature/read_feature.txt\"))\n check_path(os.path.join(options.output,\n \"temp/coverage/fragment_coverage.txt\"))\n check_path(os.path.join(options.output,\n \"temp/read_breakpoint/read_breakpoint_per_window.txt\"))\n check_path(os.path.join(options.output,\n \"temp/pileup/pileup_feature.txt\"))\n check_path(os.path.join(options.output,\n \"temp/KAD/KAD_window_data.txt\"))\n\n\ndef predict(options, data):\n # identify misassembled metagenomic contigs\n min_length = options.min_length\n test_data = data.loc[data['length'] > min_length, data.columns != 'length']\n modelfilename = '/'.join([\"model\", options.assembler])\n model_path = os.path.join(base_path, modelfilename)\n if not os.path.exists(model_path):\n f = model_path\n sys.stderr.write(\n f\"Error: Expected training model '{f}' does not exist\\n\")\n sys.exit(1)\n score = pd.DataFrame(np.zeros([test_data.shape[0], 10]))\n score.index = test_data.index\n for i in range(10):\n rf = joblib.load(model_path + \"/RF\" + str(i) + '.pkl')\n pro = pd.DataFrame(rf.predict_proba(test_data))\n pro.index = test_data.index\n score.loc[pro.index, i] = pro[1]\n score['metaMIC_contig_score'] = score.mean(axis=1)\n score = score.loc[:, ['metaMIC_contig_score']]\n score['length'] = data.loc[score.index, 'length']\n os.makedirs(options.output, exist_ok=True)\n score.to_csv(os.path.join(options.output, \"metaMIC_contig_score.txt\"), sep=\"\\t\")\n return score\n\n\ndef findcut(options, score):\n # score cutoff for identify candidate misassembled contigs\n if options.assembler == 'MEGAHIT':\n score_cut = 0.8\n elif options.assembler == 'IDBA_UD':\n score_cut = 0.5\n else:\n score_cut = np.percentile(score['metaMIC_contig_score'], 95)\n score_cut = round(score_cut * 10) / 10\n return score_cut\n\n\ndef Isolation_forest(options, window_data):\n \"\"\"\n Isolation Forest\n \"\"\"\n Xdata = window_data.loc[:, window_features]\n Xdata = Xdata.fillna(0)\n Xdata = Xdata.replace(np.inf, 0)\n n_samples = Xdata.shape[0]\n if options.mode == 'meta':\n iso_parameter = {\"outlier_fraction\": 0.001, \"outlier_threshold\": 0.01}\n else:\n iso_parameter = {\n \"outlier_fraction\": 0.0001,\n \"outlier_threshold\": 0.001}\n # fit the model\n score_pred = np.zeros([n_samples])\n for i in range(5):\n clf = IsolationForest(contamination=iso_parameter[\"outlier_fraction\"])\n clf.fit(Xdata)\n score_pred += clf.decision_function(Xdata)\n score_pred = score_pred / 5\n Xdata['anomaly_score'] = 1 - score_pred\n threshold = stats.scoreatpercentile(\n 1 - score_pred, 100 * (1 - iso_parameter[\"outlier_threshold\"]))\n Xdata['anomaly_thred'] = threshold\n score_pred_data = Xdata.loc[:, ['anomaly_score',\n 'anomaly_thred', 'read_breakpoint_ratio']]\n score_pred_data['start_pos'] = [\n int(x.split(\"_\")[-1]) for x in score_pred_data.index]\n score_pred_data['contig'] = ['_'.join(x.split(\"_\")[:-1])\n for x in score_pred_data.index]\n return score_pred_data\n\n\ndef breakpoint_detect(options, data):\n \"\"\"\n Localize misassembly breakpoints in single genomic/metagenomic assemblies\n \"\"\"\n if not os.path.exists(os.path.join(options.output,\n \"temp/read_breakpoint/read_breakpoint_per_base.txt\")):\n f = os.path.join(options.output,\n \"temp/read_breakpoint/read_breakpoint_per_base.txt\")\n sys.stderr.write(f\"Error: Expected file '{f}' does not exist\\n\")\n sys.exit(1)\n\n read_breakpoint = pd.read_csv(os.path.join(options.output,\n \"temp/read_breakpoint/read_breakpoint_per_base.txt\"), sep=\"\\t\", index_col=0)\n read_breakpoint['start_pos'] = [int(x) * 100 + 300 for x in list((read_breakpoint['position'] - 300) / 100)]\n data.index = data['contig'] + \"_\" + [str(int(x)) for x in data['start_pos']]\n if options.mode == \"single\":\n score_pred_data = Isolation_forest(options, data)\n score_pred_data.to_csv(options.output + \"/anomaly_score.txt\", sep=\"\\t\")\n score_pred_data = score_pred_data.loc[score_pred_data['anomaly_score'] > 0.95, ]\n score_pred_data.index = range(score_pred_data.shape[0])\n result = pd.merge(\n read_breakpoint, score_pred_data, on=[\n 'contig', 'start_pos'])\n result = result.iloc[np.argsort(-result['read_breakpoint_count']), ]\n result['id'] = result['contig'] + \"_\" + \\\n [str(int(x)) for x in result['start_pos']]\n result = result.drop_duplicates(['id'])\n result = result.loc[result['read_breakpoint_count'] /\n result['read_count'] > 0.2, ]\n result = result.loc[result['read_breakpoint_count'] > 5, ]\n contig_len = data.loc[:, ['contig', 'length']].drop_duplicates()\n contig_len.index = contig_len['contig']\n result['contig_length'] = list(\n contig_len.loc[result['contig'], 'length'])\n breakpoint_result = result.loc[:,\n [\"contig\",\n \"position\",\n \"read_breakpoint_count\",\n \"read_breakpoint_ratio\",\n \"anomaly_score\",\n \"anomaly_thred\",\n \"contig_length\"]]\n breakpoint_result.columns = [\n \"contig\",\n \"misassembly_breakpoint\",\n \"read_breakpoint_count\",\n \"read_breakpoint_ratio\",\n \"anomaly_score\",\n \"anomaly_thred\",\n \"contig_length\"]\n breakpoint_result.to_csv(os.path.join(options.output,\n \"misassembly_breakpoint.txt\"), sep=\"\\t\")\n else:\n if not os.path.exists(os.path.join(options.output, 'metaMIC_contig_score.txt')):\n f = options.contig_score\n sys.stderr.write(f\"Error: Expected file '{f}' does not exist\\n\")\n sys.exit(1)\n\n contig_score = pd.read_csv(os.path.join(options.output, 'metaMIC_contig_score.txt'), sep=\"\\t\", index_col=0)\n if options.score_thred:\n score_cut = options.score_thred\n else:\n score_cut = findcut(options, contig_score)\n filtered = contig_score.loc[contig_score['metaMIC_contig_score'] > score_cut, ]\n data = data[data['contig'].isin(filtered.index)]\n score_pred_data = Isolation_forest(options, data)\n score_pred_data.index = range(score_pred_data.shape[0])\n score_pred_data.to_csv(os.path.join(options.output, \"anomaly_score.txt\"), sep=\"\\t\")\n score_pred_data = score_pred_data.iloc[np.argsort( -score_pred_data['anomaly_score']), ]\n score_pred_data = score_pred_data.drop_duplicates(['contig'], keep='first')\n contig_breakpoints = score_pred_data.loc[:, ['contig', 'start_pos', 'anomaly_score',\n 'anomaly_thred', 'read_breakpoint_ratio']]\n result = pd.merge(read_breakpoint, contig_breakpoints, on=['contig', 'start_pos'], how='right')\n result['read_breakpoint_count'] = result['read_breakpoint_count'].fillna(0)\n result['position'] = result['position'].fillna(0)\n result = result.iloc[np.argsort(-result['read_breakpoint_count']), ]\n result = result.drop_duplicates(['contig'], keep='first')\n result.loc[result['position'] == 0, 'position'] = result.loc[result['position'] == 0, 'start_pos'] + 50\n result['contig_length'] = list(filtered.loc[result['contig'], 'length'])\n result['metaMIC_contig_score'] = list(filtered.loc[result['contig'], 'metaMIC_contig_score'])\n breakpoint_result = result.loc[:,\n [\"contig\",\n \"position\",\n \"read_breakpoint_count\",\n \"read_breakpoint_ratio\",\n \"anomaly_score\",\n \"anomaly_thred\",\n \"metaMIC_contig_score\",\n \"contig_length\"]]\n breakpoint_result.columns = [\n 'contig',\n 'misassembly_breakpoint',\n 'read_breakpoint_count',\n 'read_breakpoint_ratio',\n 'anomaly_score',\n \"anomaly_thred\",\n 'metaMIC_contig_score',\n \"contig_length\"]\n breakpoint_result.to_csv(os.path.join(options.output,\n \"misassembly_breakpoint.txt\"), sep=\"\\t\")\n return breakpoint_result\n\n\ndef correct(options, breakpoint_result):\n \"\"\"\n Correct misassemblies\n \"\"\"\n breakpoint_result = breakpoint_result.loc[breakpoint_result['misassembly_breakpoint']\n > options.split_length, ]\n breakpoint_result = breakpoint_result.loc[(breakpoint_result['contig_length'] - breakpoint_result['misassembly_breakpoint'])\n > options.split_length, ]\n breakpoint_result = breakpoint_result.loc[breakpoint_result['read_breakpoint_count']\n > options.break_count, ]\n breakpoint_result = breakpoint_result.loc[breakpoint_result['read_breakpoint_ratio']\n > options.break_ratio, ]\n breakpoint_result = breakpoint_result.loc[breakpoint_result['anomaly_score']\n > options.anomaly_thred, ]\n corrected_contig_file = os.path.join(options.output, \"metaMIC_corrected_contigs.fa\")\n corrected_file = open(corrected_contig_file, \"w\")\n original_file = options.assemblies\n input = SeqIO.parse(original_file, \"fasta\")\n breakcontigs = list(np.unique(breakpoint_result['contig']))\n for record in input:\n if record.id in breakcontigs:\n corrected_file.write(\">\" + record.id + \"_1\\n\")\n breakpoint = int(list(breakpoint_result.loc[breakpoint_result['contig'] == record.id, 'misassembly_breakpoint'])[0])\n corrected_file.write(str(record.seq[:breakpoint]) + \"\\n\")\n corrected_file.write(\">\" + record.id + \"_2\\n\")\n corrected_file.write(str(record.seq[breakpoint:]) + \"\\n\")\n else:\n corrected_file.write(\">\" + record.id + \"\\n\")\n corrected_file.write(str(record.seq) + \"\\n\")\n corrected_file.close()\n print(\"A total of \" + str(breakpoint_result.shape[0]) + \" misassembled contigs are corrected\")\n\nfrom .train import train\ndef train_model(options, data):\n train(data, options)\n\n\ndef bamindex(options):\n command_index = options.samtools + ' index ' + options.bamfile\n os.system(command_index)\n\n\ndef validate_options(options):\n def expect_file(f):\n if f is not None:\n if not os.path.exists(f):\n sys.stderr.write(\n f\"Error: Expected file '{f}' does not exist\\n\")\n sys.exit(1)\n\n def expect_mode(f):\n if f not in ['single', 'meta']:\n options.mode = 'meta'\n logging.warning(\"Using default mode: [meta]\")\n\n if options.cmd != 'download_model':\n if not os.path.exists(options.output):\n os.makedirs(options.output, exist_ok=True)\n\n if options.cmd == 'extract_feature':\n if os.path.exists(os.path.join(options.output, \"temp/contig/filtered_contigs.fa\")):\n options.assemblies = os.path.join(options.output, \"temp/contig/filtered_contigs.fa\")\n else:\n expect_file(options.assemblies)\n options = filter_contig(options)\n expect_file(options.pileup)\n expect_mode(options.mode)\n if options.bamfile is not None:\n expect_file(options.bamfile)\n bamindex(options)\n else:\n if options.read is None and (options.read1 is None or options.read2 is None):\n sys.stderr.write(\n f\"Error: Expected read1 and read2.\\n\")\n sys.exit(1)\n\n if options.read and (options.read1 or options.read2):\n sys.stderr.write(\n f\"Input read1/read2 or smart pairing (ignoring #2 fasta/q).\\n\")\n sys.exit(1)\n\n if os.path.exists(os.path.join(options.output, \"temp/sam/contig.filter.sort.bam\")):\n options.bamfile = os.path.join(options.output, \"temp/sam/contigs.filter.sort.bam\")\n else:\n print(\"Bamfile not exists, Mapping paired-end reads to assemblies\")\n options = mapping(options)\n\n if not os.path.exists(options.bamfile):\n f = options.bamfile\n sys.stderr.write(f\"Error: Expected file '{f}' does not exist\\n\")\n sys.exit(1)\n\n if options.cmd == 'train':\n if options.label is None:\n sys.stderr.write(\n \"Error: misassembly labels of training contigs does not exist\\n\")\n sys.exit(1)\n elif not os.path.exists(options.label):\n f = options.label\n sys.stderr.write(f\"Error: Expected file '{f}' does not exist\\n\")\n sys.exit(1)\n if options.assembler in [\"MEGAHIT\", \"IDBA_UD\"]:\n sys.stderr.write(\n \"Error: Name is same as the default model, change to another name not in [MEGAHIT, IDBA_UD].\\n\")\n sys.exit(1)\n\n if options.cmd == 'predict':\n if os.path.exists(os.path.join(options.output, \"temp/contig/filtered_contigs.fa\")):\n options.assemblies = os.path.join(options.output, \"temp/contig/filtered_contigs.fa\")\n else:\n expect_file(options.assemblies)\n options = filter_contig(options)\n\n expect_mode(options.mode)\n return options\n\n\ndef main():\n args = sys.argv[1:]\n options = get_opts(args)\n\n warnings.filterwarnings(\"ignore\")\n logger = logging.getLogger('metaMIC')\n logger.setLevel(logging.INFO)\n sh = logging.StreamHandler()\n sh.setFormatter(logging.Formatter('%(asctime)s - %(message)s'))\n logger.addHandler(sh)\n\n ########### Validate input files ###########\n logger.info('Start metaMIC')\n\n options = validate_options(options)\n if options.cmd == 'download_model':\n download()\n\n ########### Extract four types of features from bamfile ###########\n if options.cmd == 'extract_feature':\n logger.info('Step: Feature extraction')\n extract_feature(options)\n\n ########### Training models specified by users or not ###########\n if options.cmd == 'train':\n logger.info('Step: Training new models')\n\n train_model(options, os.path.join(options.output, 'feature_matrix/contig_fea_matrix.txt'))\n logger.info(\"Finished\")\n return 0\n\n ########### Identify misassembled contigs [for only metagenomics] ########\n if options.cmd == 'predict':\n if options.mode == 'meta':\n logger.info('Step: Identify misassembled metagenomic contigs')\n contig_data = pd.read_csv(os.path.join(options.output, 'feature_matrix/contig_fea_matrix.txt'), sep=\"\\t\", index_col=0)\n score = predict(options, contig_data)\n\n logger.info('Step: Localize misassembly breakpoints')\n window_data = pd.read_csv(os.path.join(options.output, 'feature_matrix/window_fea_matrix.txt'), sep=\"\\t\", index_col=0)\n breakpoint_result = breakpoint_detect(options, window_data)\n logger.info('Step: Correct misassemblies')\n correct(options, breakpoint_result)\n logger.info(\"Finished\")\n\nif __name__ == '__main__':\n main()\n"
] | [
[
"numpy.zeros",
"numpy.argsort",
"scipy.stats.scoreatpercentile",
"numpy.percentile",
"pandas.merge",
"pandas.concat",
"numpy.array",
"sklearn.ensemble.IsolationForest",
"numpy.unique"
]
] |
kaanberke/AI-pipelines | [
"a60c6bbe0bc0bd441f6486fcc0d513acece7fed4"
] | [
"image_classification_pipeline/dataset_builder.py"
] | [
"# %% LIBRARIES\nimport glob\nimport os\nimport random\nfrom pathlib import Path\nfrom typing import Union\n\nimport cv2\nimport pandas as pd\nimport tensorflow as tf\nfrom matplotlib import pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import class_weight\nfrom tensorflow.python.data import AUTOTUNE\nfrom tqdm import tqdm\n\n\n# %% Class\n\n\nclass Dataset(object):\n def __init__(self,\n data_directories: list[list[str, int]],\n labels: list,\n image_size: tuple[int, int],\n channels: int,\n batch_size: int,\n image_extensions: list[str]):\n \"\"\"\n\n :param data_directories: Data directories should be provided\n with the number of image that is requested to be collected. -1 = all\n :param labels: Labels for the provided data directories.\n :param image_size: Image size in order to resize all\n the images for the input of the model.\n :param channels: Number of channels of the image\n :param image_extensions: Extensions of images that is\n requested to be collected\n :param batch_size: Batch size for tf.data\n\n >>> d = Dataset(\n ... data_directories=[\n ... [\"./data/train/real/1\", -1],\n ... [\"./data/train/real/2\", -1],\n ... [\"./data/train/fake/1\", -1],\n ... [\"./data/train/fake/2\", -1],\n ... ],\n ... labels=[\"real\", \"fake\"],\n ... image_size=(240, 240),\n ... channels=3,\n ... batch_size=8,\n ... image_extensions=[\"/*.jpeg\", \"/*.jpg\", \"/*.png\"]\n ... )\n \"\"\"\n\n super(Dataset, self).__init__()\n self.data_directories = data_directories\n self.labels = labels\n self.image_size = image_size\n self.channels = channels\n self.batch_size = batch_size\n self.image_extensions = image_extensions + [ext.swapcase() for ext in image_extensions]\n\n def get_image_paths(self):\n all_data = []\n progress_bar = tqdm(self.data_directories, desc=\"data collecting\")\n for data_dir, sample_no in self.data_directories:\n files_grabbed = []\n for ext in self.image_extensions:\n files_grabbed.extend(glob.glob(str(data_dir) + ext))\n\n random.shuffle(files_grabbed)\n if sample_no == -1 or len(files_grabbed) < sample_no:\n all_data.extend(files_grabbed)\n else:\n all_data.extend(files_grabbed[:sample_no])\n progress_bar.update()\n return all_data\n\n def display_image_grid(self,\n images_filepaths: list[str],\n image_size: list[int] = (240, 240),\n predicted_labels: list[str] = None,\n cols: int = 5):\n \"\"\"\n :param images_filepaths: File paths of the images that wants be visualized.\n :param predicted_labels: Predicted labels of the given images (optional).\n :param image_size: Image size in order to resize all the given images.\n :param cols: How many columns will be on the figure.\n :return: None\n \"\"\"\n rows = len(images_filepaths) // cols\n figure, ax = plt.subplots(nrows=rows, ncols=cols, figsize=(12, 6))\n for i, image_filepath in enumerate(images_filepaths):\n image = cv2.imread(image_filepath)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n image = cv2.resize(image, image_size)\n true_label = list(\n set(self.labels).intersection(\n os.path.normpath(image_filepath).split(os.sep)\n )\n )[0]\n ax.ravel()[i].imshow(image)\n ax.ravel()[i].set_title(true_label)\n if predicted_labels:\n predicted_label = predicted_labels[i] if predicted_labels else true_label\n color = \"green\" if true_label == predicted_label else \"red\"\n ax.ravel()[i].set_title(predicted_label, color=color)\n ax.ravel()[i].set_axis_off()\n plt.tight_layout()\n plt.show()\n\n def __load_images(self,\n image_path: tf.Tensor,\n image_label: tf.Tensor,\n categorical: bool = False):\n\n image = tf.io.read_file(image_path)\n image = tf.image.decode_png(image, channels=self.channels)\n image = tf.image.resize(image, self.image_size) / 255.0\n if categorical:\n image_label = tf.one_hot(tf.strings.to_number(image_label, out_type=tf.dtypes.int32), len(self.labels))\n return image, image_label\n\n @tf.function\n def __augment_images(self,\n images: tf.Tensor,\n labels: tf.Tensor):\n images = tf.image.random_flip_left_right(images)\n images = tf.image.rot90(images)\n images = tf.image.random_flip_up_down(images)\n return images, labels\n\n def get_dataset(\n self,\n split_ratios: Union[\n tuple[float, float, float],\n tuple[float, float]] = (0.7, 0.2, 0.1),\n cache: str = \"./\",\n balanced_weights: bool = False,\n categorical: bool = True,\n show_details: bool = True):\n \"\"\"\n :param split_ratios: (train, validation, test) ratios.\n :param cache: Path that is cached values will be placed.\n :param balanced_weights: If True, Scikit-learn's class_weight function will be applied.\n :param categorical: If True labels will be returned as categorical, else binary.\n :param show_details: If True information will be printed occasionally.\n :return: (train_dataset, validation_dataset)\n + test_dataset if split_ratios length is 3.\n + class_weights if balanced_weights is True.\n \"\"\"\n\n cache_path = Path(cache)\n result = []\n all_data = self.get_image_paths()\n df = pd.DataFrame(all_data, columns=[\"image_path\"])\n df[\"label\"] = None\n\n # iterate over all the labels and substitute labels with relevant integer\n # value where the path involves the keyword (case insensitive).\n for idx, label in enumerate(self.labels):\n df.loc[(df[\"image_path\"].str.contains(label, case=False)), \"label\"] = str(idx)\n\n # Show the frequency of the labels\n if show_details:\n print(df[\"label\"].value_counts())\n print(df.tail())\n\n train_df, validation_df = train_test_split(df.sample(frac=1),\n test_size=split_ratios[1])\n\n train_dataset = tf.data.Dataset.from_tensor_slices(\n (train_df[\"image_path\"].values, train_df[\"label\"].values))\n\n train_dataset = (train_dataset\n .shuffle(len(train_df))\n .map(\n lambda image_path, image_label: self.__load_images(image_path, label, categorical),\n num_parallel_calls=AUTOTUNE)\n .batch(self.batch_size)\n .cache(str(cache_path / \"train_dataset\"))\n .prefetch(AUTOTUNE))\n result.append(train_dataset)\n\n if len(split_ratios) == 3:\n test_size = split_ratios[2] / (split_ratios[1] + split_ratios[2])\n validation_dataset = tf.data.Dataset.from_tensor_slices(\n (validation_df[\"image_path\"].values, validation_df[\"label\"].values))\n validation_dataset = (validation_dataset\n .shuffle(len(validation_df))\n .map(\n lambda images, labels: self.__load_images(images, labels, categorical),\n num_parallel_calls=AUTOTUNE, )\n .batch(self.batch_size)\n .cache(str(cache_path / \"validation_dataset\"))\n .prefetch(AUTOTUNE))\n\n result.append(validation_dataset)\n\n validation_df, test_df = train_test_split(validation_df.sample(frac=1),\n test_size=test_size)\n\n test_dataset = tf.data.Dataset.from_tensor_slices(\n (test_df[\"image_path\"].values, test_df[\"label\"].values))\n test_dataset = (test_dataset\n .shuffle(len(test_df))\n .map(\n lambda images, labels: self.__load_images(images, labels, categorical),\n num_parallel_calls=AUTOTUNE, )\n .batch(1)\n .cache(str(cache_path / \"test_dataset\"))\n .prefetch(AUTOTUNE))\n result.append(test_dataset)\n elif len(split_ratios) == 2:\n validation_dataset = tf.data.Dataset.from_tensor_slices(\n (validation_df[\"image_path\"].values, validation_df[\"label\"].values))\n\n validation_dataset = (validation_dataset\n .shuffle(len(validation_df))\n .map(\n lambda images, labels: self.__load_images(images, labels, categorical),\n num_parallel_calls=AUTOTUNE, )\n .batch(self.batch_size)\n .cache(str(cache_path / \"validation_dataset\"))\n .prefetch(AUTOTUNE))\n\n result.append(validation_dataset)\n else:\n raise ValueError(\"Improper value for split_ratios parameter\")\n\n if balanced_weights:\n class_weights = class_weight.compute_class_weight(\n \"balanced\", classes=df[\"label\"].unique(), y=df[\"label\"])\n class_weights = dict(enumerate(class_weights))\n print(f\"{class_weights=}\")\n result.append(class_weights)\n\n return result\n"
] | [
[
"tensorflow.image.random_flip_up_down",
"tensorflow.image.rot90",
"tensorflow.image.random_flip_left_right",
"tensorflow.image.resize",
"matplotlib.pyplot.tight_layout",
"pandas.DataFrame",
"tensorflow.strings.to_number",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show",
"tensorflow.io.read_file",
"tensorflow.image.decode_png",
"tensorflow.data.Dataset.from_tensor_slices"
]
] |
ddlee-cn/SemIA | [
"46114d37b09df3675d4a8285bf9d3de5242758b6"
] | [
"test.py"
] | [
"import os\nfrom collections import OrderedDict\nimport torch\n\nfrom options.test_options import TestOptions\nfrom semia.model import SemIAModel\nfrom semia.dataset import TestImgDataset\nfrom util.visualizer import Visualizer\nfrom util.util import read_image, pil2tensor, pil2np, np2tensor\n\n\nif __name__ == \"__main__\":\n TestOptions = TestOptions()\n opt = TestOptions.parse()\n\n # Prepare data\n test_dataset = TestImgDataset()\n test_dataset.initialize(opt)\n # record input_image size\n opt.width, opt.height = test_dataset.width, test_dataset.height\n\n test_dataloader = torch.utils.data.DataLoader(test_dataset, batch_size=1, shuffle=False, num_workers=1,drop_last=False)\n\n\n opt.gpu = 0\n opt.mpdist = False\n\n model = SemIAModel(opt)\n model.eval()\n\n visualizer = Visualizer(opt)\n\n out_root = os.path.join(opt.output_dir, opt.name)\n if not os.path.isdir(out_root):\n os.mkdir(out_root)\n\n for i, test_data in enumerate(test_dataloader):\n name = test_dataset.test_names[i]\n model.set_input(test_data, 'inference')\n eval_image = model.evaluate()\n visuals = {'./': eval_image}\n visualizer.save_images(out_root, visuals, name)"
] | [
[
"torch.utils.data.DataLoader"
]
] |
Saoge123/ccgnet | [
"9359c642bd1faa4c15cae829615385761ebd8d92"
] | [
"BayesOpt/BayesOpt-GraphCNN.py"
] | [
"import sys\nimport os\nsys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))\nfrom ccgnet import experiment as exp\nfrom ccgnet import layers\nimport tensorflow as tf\nimport numpy as np\nimport time\nfrom sklearn.metrics import balanced_accuracy_score\nfrom ccgnet.Dataset import Dataset, DataLoader\n\n\n\ndef build_model(\n graphcnn_layer_1_size, \n graphcnn_layer_2_size,\n graphcnn_layer_3_size,\n graphcnn_act_fun,\n graph_pool_1_size,\n graph_pool_2_size,\n graph_pool_3_size,\n graph_pool_act_fun,\n dense_layer_1_size, \n dense_layer_2_size,\n dense_layer_3_size,\n dense_act_func, \n dense_dropout\n ):\n mask_judge = (graph_pool_1_size, graph_pool_2_size, graph_pool_3_size)\n print(mask_judge)\n class Model(object):\n def build_model(self, inputs, is_training, global_step):\n V = inputs[0]\n A = inputs[1]\n labels = inputs[2]\n mask = inputs[3]\n graph_size = inputs[4]\n tags = inputs[5]\n # Graph-CNN stage\n V = layers.make_graphcnn_layer(V, A, graphcnn_layer_1_size)\n V = layers.make_bn(V, is_training, mask=mask, num_updates=global_step)\n V = graphcnn_act_fun(V)\n if graph_pool_1_size != None:\n V_pool, A = layers.make_graph_embed_pooling(V, A, mask=mask, no_vertices=graph_pool_1_size)\n V = layers.make_bn(V_pool, is_training, mask=None, num_updates=global_step)\n V = graph_pool_act_fun(V)\n if graphcnn_layer_2_size != None:\n if mask_judge[0] != None:\n m = None\n else:\n m = mask\n V = layers.make_graphcnn_layer(V, A, graphcnn_layer_2_size)\n V = layers.make_bn(V, is_training, mask=m, num_updates=global_step)\n V = graphcnn_act_fun(V)\n if graph_pool_2_size != None:\n if mask_judge[0] != None:\n m = None\n else:\n m = mask\n V_pool, A = layers.make_graph_embed_pooling(V, A, mask=m, no_vertices=graph_pool_2_size)\n V = layers.make_bn(V_pool, is_training, mask=None, num_updates=global_step)\n V = graph_pool_act_fun(V)\n if graphcnn_layer_3_size != None:\n if mask_judge[1] != None or mask_judge[0] != None:\n m = None\n else:\n m = mask\n V = layers.make_graphcnn_layer(V, A, graphcnn_layer_3_size)\n V = layers.make_bn(V, is_training, mask=m, num_updates=global_step)\n V = graphcnn_act_fun(V)\n \n if mask_judge[1] != None or mask_judge[0] != None:\n m = None\n else:\n m = mask\n V_pool, A = layers.make_graph_embed_pooling(V, A, mask=m, no_vertices=graph_pool_3_size)\n V = layers.make_bn(V_pool, is_training, mask=None, num_updates=global_step)\n V = graph_pool_act_fun(V)\n \n # Predictive Stage\n no_input_features = int(np.prod(V.get_shape()[1:]))\n V = tf.reshape(V, [-1, no_input_features])\n V = layers.make_embedding_layer(V, dense_layer_1_size, name='FC-1')\n V = layers.make_bn(V, is_training, mask=None, num_updates=global_step)\n V = dense_act_func(V)\n V = tf.compat.v1.layers.dropout(V, dense_dropout, training=is_training)\n if dense_layer_2_size != None:\n V = layers.make_embedding_layer(V, dense_layer_2_size, name='FC-2')\n V = layers.make_bn(V, is_training, mask=None, num_updates=global_step)\n V = dense_act_func(V)\n V = tf.compat.v1.layers.dropout(V, dense_dropout, training=is_training)\n if dense_layer_3_size != None:\n V = layers.make_embedding_layer(V, dense_layer_3_size, name='FC-3')\n V = layers.make_bn(V, is_training, mask=None, num_updates=global_step)\n V = dense_act_func(V)\n V = tf.compat.v1.layers.dropout(V, dense_dropout, training=is_training)\n \n out = layers.make_embedding_layer(V, 2, name='final')\n return out, labels\n return Model()\n\ndef black_box_function(args_dict):\n \n tf.reset_default_graph()\n batch_size = args_dict['batch_size']\n graphcnn_layer_1_size = args_dict['graphcnn_layer_1_size']\n graphcnn_layer_2_size = args_dict['graphcnn_layer_2_size']\n graphcnn_layer_3_size = args_dict['graphcnn_layer_3_size']\n graphcnn_act_fun = args_dict['graphcnn_act_fun']\n graph_pool_1_size = args_dict['graph_pool_1_size']\n graph_pool_2_size = args_dict['graph_pool_2_size']\n graph_pool_3_size = args_dict['graph_pool_3_size']\n graph_pool_act_fun = args_dict['graph_pool_act_fun']\n dense_layer_1_size = args_dict['dense_layer_1_size']\n dense_layer_2_size = args_dict['dense_layer_2_size']\n dense_layer_3_size = args_dict['dense_layer_3_size']\n dense_act_func = args_dict['dense_act_func']\n dense_dropout = args_dict['dense_dropout']\n \n # make save dir\n snapshot_path = abs_path+'/bayes_snapshot/'\n model_name = 'BayesOpt-GraphCNN/'\n verify_dir_exists(snapshot_path+model_name)\n if os.listdir(snapshot_path+model_name) == []:\n dataset_name = 'Step_0/'\n else:\n l_ = [int(i.split('_')[1]) for i in os.listdir(snapshot_path+model_name) if 'Step_' in i]\n dataset_name = 'Step_{}/'.format(max(l_)+1)\n \n model = build_model(graphcnn_layer_1_size, \n graphcnn_layer_2_size, \n graphcnn_layer_3_size, \n graphcnn_act_fun, \n graph_pool_1_size, \n graph_pool_2_size, \n graph_pool_3_size, \n graph_pool_act_fun,\n dense_layer_1_size, \n dense_layer_2_size, \n dense_layer_3_size, \n dense_act_func, \n dense_dropout)\n model = exp.Model(model, train_data, valid_data, with_test=False, snapshot_path=snapshot_path, use_subgraph=False, use_desc=False, build_fc=False,\n model_name=model_name, dataset_name=dataset_name+'/time_0')\n history = model.fit(num_epoch=100, save_info=True, save_att=False, silence=False, train_batch_size=batch_size, \n max_to_keep=1, metric='loss')\n loss = min(history['valid_cross_entropy'])\n tf.reset_default_graph()\n print('\\nLoss: {}'.format(loss))\n print(str(args_dict))\n return loss\n\n\nfrom hyperopt import fmin, tpe, Trials, hp\nimport hyperopt.pyll.stochastic\nimport random\n\n\ndef verify_dir_exists(dirname):\n if os.path.isdir(os.path.dirname(dirname)) == False:\n os.makedirs(os.path.dirname(dirname))\n\ndef make_dataset():\n data1 = Dataset(abs_path+'/CC_Table/CC_Table.tab', mol_blocks_dir=abs_path+'/Mol_Blocks.dir')\n data1.make_graph_dataset(Desc=0, A_type='OnlyCovalentBond', hbond=0, pipi_stack=0, contact=0, make_dataframe=True)\n return data1\n\nabs_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))\nfold_10 = eval(open(abs_path+'/Fold_10.dir').read())\ndata = make_dataset()\nSamples = fold_10['fold-0']['train']+fold_10['fold-0']['valid']\n\n# data spliting\nrandom.shuffle(Samples)\nnum_sample = len(Samples)\ntrain_num = int(0.9 * num_sample)\ntrain_samples = Samples[:train_num]\nvalid_samples = Samples[train_num:]\ntrain_data, valid_data = data.split(train_samples=train_samples, valid_samples=valid_samples)\n\nargs_dict = {\n 'batch_size':hp.choice('batch_size', (128,)),\n 'graphcnn_layer_1_size':hp.choice('graphcnn_layer_1_size', (16,32,64,128,256)),\n 'graphcnn_layer_2_size':hp.choice('graphcnn_layer_2_size', (16,32,64,128,256,None)),\n 'graphcnn_layer_3_size':hp.choice('graphcnn_layer_3_size', (16,32,64,128,256,None)),\n 'graphcnn_act_fun':hp.choice('graphcnn_act_fun', (tf.nn.relu, )), \n 'graph_pool_1_size':hp.choice('graph_pool_1_size', (8,16,32,None)),\n 'graph_pool_2_size':hp.choice('graph_pool_2_size', (8,16,32,None)),\n 'graph_pool_3_size':hp.choice('graph_pool_3_size', (8,16,32)),\n 'graph_pool_act_fun':hp.choice('graph_pool_act_fun', (tf.nn.relu, )),\n 'dense_layer_1_size':hp.choice('dense_layer_1_size', (64,128,256,512)),\n 'dense_layer_2_size':hp.choice('dense_layer_2_size', (64,128,256,512,None)),\n 'dense_layer_3_size':hp.choice('dense_layer_3_size', (64,128,256,512,None)),\n 'dense_act_func':hp.choice('dense_act_func', (tf.nn.relu, )),\n 'dense_dropout':hp.uniform('dense_dropout', 0.0, 0.75)\n }\ntrials = Trials()\nbest = fmin(\n fn=black_box_function,\n space=args_dict,\n algo=tpe.suggest,\n max_evals=100,\n trials=trials,\n trials_save_file='trials_save_file-graphcnn')\nprint('\\nbest:')\nprint(best)"
] | [
[
"tensorflow.compat.v1.layers.dropout",
"tensorflow.reset_default_graph",
"tensorflow.reshape"
]
] |
locuslab/e2e-model-learning | [
"2bf43848ac26e25321fea7bfeddf2a24135aa192"
] | [
"battery_storage/main.py"
] | [
"#!/usr/bin/env python3\n\nimport argparse\nimport setproctitle\n\nimport scipy.io as sio\nimport numpy as np\n\nimport torch\n\nimport importlib\ntry: import setGPU\nexcept ImportError: pass\n\nimport os\n\nimport model_classes, nets, calc_stats\nfrom constants import *\n\nfrom torch.utils.data import DataLoader, TensorDataset\n\nimport pandas as pd\nfrom datetime import datetime as dt\nimport pytz\nfrom pandas.tseries.holiday import USFederalHolidayCalendar\n\ndef main():\n parser = argparse.ArgumentParser(\n description='Run storage task net experiments.')\n parser.add_argument('--save', type=str, \n metavar='save-folder', help='prefix to add to save path')\n parser.add_argument('--nRuns', type=int, default=10,\n metavar='runs', help='number of runs')\n parser.add_argument('--paramSet', type=int, choices=range(4), default=0,\n metavar='hyperparams', help='(lambda, epsilon) in given row of Table 1')\n args = parser.parse_args()\n\n\n save_folder_main = 'params{}'.format(args.paramSet) if args.save is None \\\n else '{}-params{}'.format(args.save, args.paramSet)\n save_folder_main = os.path.join('results', save_folder_main)\n\n setproctitle.setproctitle('storage-{}'.format(args.paramSet))\n\n # Initialize problem parameters\n params = init_params(args.paramSet)\n\n bsz = 500\n\n # Train, test split\n train_frac = 0.8\n\n input_tensors = get_train_test_split(params, train_frac)\n loaders = get_loaders_tt(input_tensors, bsz)\n\n if not os.path.exists(save_folder_main):\n os.makedirs(save_folder_main)\n\n for run in range(args.nRuns):\n\n save_folder = os.path.join(save_folder_main, str(run))\n if not os.path.exists(save_folder):\n os.makedirs(save_folder)\n\n # Randomly construct hold-out set for task net training.\n tensors_task = get_train_hold_split(input_tensors, 0.8, save_folder)\n loaders_task = get_loaders_tth(tensors_task, bsz)\n\n # Run and eval rmse-minimizing net\n model_rmse = model_classes.Net(\n tensors_task['X_train'], tensors_task['Y_train'], [200, 200], params['T'])\n if USE_GPU:\n model_rmse = model_rmse.cuda()\n model_rmse = nets.run_rmse_net(model_rmse, loaders_task, params, tensors_task)\n nets.eval_net('rmse_net', model_rmse, loaders_task, params, save_folder)\n\n # Run and eval task-minimizing net\n model_task = model_classes.Net(\n tensors_task['X_train'], tensors_task['Y_train'], [200, 200], params['T'])\n if USE_GPU:\n model_task = model_task.cuda()\n model_task = nets.run_rmse_net(model_task, loaders_task, params, tensors_task) # seed with rmse soln\n model_task = \\\n nets.run_task_net(model_task, loaders_task, params, args, tensors_task)\n nets.eval_net('task_net', model_task, loaders_task, params, save_folder)\n\n calc_stats.calc_stats(map(\n lambda x: os.path.join(save_folder_main, str(x)), range(args.nRuns)), save_folder_main)\n\n\ndef init_params(param_set):\n\n # potential (lambda, epsilon) pairs for experiment\n hyperparams = [[0.1, 0.05], [1, 0.5], [10, 5], [35, 15]]\n\n params = {}\n\n # Battery capacity\n params['B'] = 1\n\n # Battery efficiency\n params['eff'] = 0.9\n\n # Battery max power in\n params['in_max'] = 0.5\n \n # Battery max power out\n params['out_max'] = 0.2\n \n # Number of horizons\n params['T'] = 24\n\n # Preference for battery staying in middle of range\n params['lambda'] = hyperparams[param_set][0]\n\n # Regularize z_in and z_out\n params['epsilon'] = hyperparams[param_set][1]\n\n return params\n\n\ndef get_features_labels(params):\n # TODO predict lmp instead of energy price?\n tz = pytz.timezone('America/New_York')\n df = pd.read_csv('storage_data.csv', parse_dates=[0])\n df['date'] = df['datetime'].apply(lambda x: x.date())\n df['hour'] = df['datetime'].apply(lambda x: x.hour)\n\n # Prices\n df_prices = df.pivot(index='date', columns='hour', values='da_price')\n df_prices = df_prices.apply(lambda x: pd.to_numeric(x), axis=1)\n df_prices = df_prices.transpose().fillna(method='backfill').transpose()\n df_prices = df_prices.transpose().fillna(method='ffill').transpose()\n\n # Filtering some outliers\n df_prices_filtered = df_prices.applymap(lambda x: np.nan if x > 500 else x).dropna()\n df_prices_filtered = df_prices_filtered.applymap(lambda x: np.nan if x <= 0 else x).dropna()\n\n df_prices_log_filtered = np.log(df_prices_filtered)\n\n # Load forecasts\n df_load = df.pivot(index='date', columns='hour', values='load_forecast')\n df_load = df_load.apply(lambda x: pd.to_numeric(x), axis=1)\n df_load = df_load.transpose().fillna(method='backfill').transpose()\n df_load = df_load.transpose().fillna(method='ffill').transpose()\n df_load = df_load.reindex(df_prices_log_filtered.index)\n\n # Temperatures\n df_temp = df.pivot(index='date', columns='hour', values='temp_dca')\n df_temp = df_temp.apply(lambda x: pd.to_numeric(x), axis=1)\n df_temp = df_temp.transpose().fillna(method='backfill').transpose()\n df_temp = df_temp.transpose().fillna(method='ffill').transpose()\n df_temp = df_temp.reindex(df_prices_log_filtered.index)\n\n holidays = USFederalHolidayCalendar().holidays(\n start='2011-01-01', end='2017-01-01').to_pydatetime()\n holiday_dates = set([h.date() for h in holidays])\n\n s = df_prices_log_filtered.reset_index()['date']\n data={\"weekend\": s.apply(lambda x: x.isoweekday() >= 6).values,\n \"holiday\": s.apply(lambda x: x in holiday_dates).values,\n \"dst\": s.apply(lambda x: tz.localize(\n dt.combine(x, dt.min.time())).dst().seconds > 0).values,\n \"cos_doy\": s.apply(lambda x: np.cos(\n float(x.timetuple().tm_yday)/365*2*np.pi)).values,\n \"sin_doy\": s.apply(lambda x: np.sin(\n float(x.timetuple().tm_yday)/365*2*np.pi)).values}\n df_feat = pd.DataFrame(data=data, index=df_prices_log_filtered.index)\n\n X = np.hstack([df_prices_log_filtered.iloc[:-1].values, # past lmp\n df_load.iloc[1:].values, # future load forecast\n df_temp.iloc[:-1].values, # past temp\n df_temp.iloc[:-1].values**2, # past temp^2\n df_temp.iloc[1:].values, # future temp\n df_temp.iloc[1:].values**2, # future temp^2\n df_temp.iloc[1:].values**3, # future temp^3\n df_feat.iloc[1:].values]).astype(np.float64)\n\n X[:,:] = \\\n (X[:,:] - np.mean(X[:,:], axis=0)) / np.std(X[:,:], axis=0)\n\n Y = df_prices_log_filtered.iloc[1:].values\n\n return X, Y\n\n\ndef get_train_test_split(params, train_frac):\n X, Y = get_features_labels(params)\n\n n_tt = int(X.shape[0] * 0.8)\n X_train, Y_train = X[:n_tt, :], Y[:n_tt, :]\n X_test, Y_test = X[n_tt:, :], Y[n_tt:, :]\n\n arrays = {'X_train': torch.Tensor(X_train), 'Y_train': torch.Tensor(Y_train), \n 'X_test': torch.Tensor(X_test), 'Y_test': torch.Tensor(Y_test)}\n\n return arrays\n\ndef get_loaders_tt(arrays_dict, bsz):\n train_loader = DataLoader(TensorDataset(\n arrays_dict['X_train'], arrays_dict['Y_train']), shuffle=False, batch_size=bsz)\n test_loader = DataLoader(TensorDataset(\n arrays_dict['X_test'], arrays_dict['Y_test']), shuffle=False, batch_size=bsz)\n return {'train': train_loader, 'test': test_loader}\n\ndef get_loaders_tth(arrays_dict, bsz):\n train_loader = DataLoader(TensorDataset(\n arrays_dict['X_train'], arrays_dict['Y_train']), shuffle=False, batch_size=bsz)\n test_loader = DataLoader(TensorDataset(\n arrays_dict['X_test'], arrays_dict['Y_test']), shuffle=False, batch_size=bsz)\n hold_loader = DataLoader(TensorDataset(\n arrays_dict['X_hold'], arrays_dict['Y_hold']), shuffle=False, batch_size=bsz)\n return {'train': train_loader, 'test': test_loader, 'hold': hold_loader}\n\ndef get_train_hold_split(tensors_dict, th_frac, save_folder):\n X_train = tensors_dict['X_train']\n Y_train = tensors_dict['Y_train']\n\n inds = np.random.permutation(X_train.size(0))\n\n with open(os.path.join(save_folder, 'th_split_permutation'), 'wb') as f:\n np.save(f, inds)\n\n train_inds = torch.LongTensor(inds[ :int(X_train.size(0) * th_frac)])\n hold_inds = torch.LongTensor(inds[int(X_train.size(0) * th_frac):])\n\n X_train2, X_hold2 = X_train[train_inds, :], X_train[hold_inds, :]\n Y_train2, Y_hold2 = Y_train[train_inds, :], Y_train[hold_inds, :]\n\n tensors_task = {'X_train': X_train2, 'Y_train': Y_train2, \n 'X_hold': X_hold2, 'Y_hold': Y_hold2,\n 'X_test': tensors_dict['X_test'].clone(),\n 'Y_test': tensors_dict['Y_test'].clone()}\n return tensors_task\n\nif __name__=='__main__':\n main()\n\n\n"
] | [
[
"pandas.tseries.holiday.USFederalHolidayCalendar",
"numpy.save",
"pandas.read_csv",
"pandas.to_numeric",
"pandas.DataFrame",
"numpy.hstack",
"numpy.log",
"numpy.mean",
"numpy.std",
"torch.utils.data.TensorDataset",
"torch.Tensor"
]
] |
EStorm21/kornia | [
"b2bba7950d748ba0b8ce0cc68035a248799a1044"
] | [
"kornia/geometry/bbox.py"
] | [
"from typing import Tuple\n\nimport torch\n\nimport kornia\n\n\[email protected]\ndef validate_bbox(boxes: torch.Tensor) -> bool:\n \"\"\"Validate if a 2D bounding box usable or not. This function checks if the boxes are rectangular or not.\n\n Args:\n boxes: a tensor containing the coordinates of the bounding boxes to be extracted. The tensor must have the shape\n of Bx4x2, where each box is defined in the following ``clockwise`` order: top-left, top-right, bottom-right,\n bottom-left. The coordinates must be in the x, y order.\n \"\"\"\n if not (len(boxes.shape) == 3 and boxes.shape[1:] == torch.Size([4, 2])):\n raise AssertionError(f\"Box shape must be (B, 4, 2). Got {boxes.shape}.\")\n\n if not torch.allclose((boxes[:, 1, 0] - boxes[:, 0, 0] + 1), (boxes[:, 2, 0] - boxes[:, 3, 0] + 1)):\n raise ValueError(\n \"Boxes must have be rectangular, while get widths %s and %s\"\n % (str(boxes[:, 1, 0] - boxes[:, 0, 0] + 1), str(boxes[:, 2, 0] - boxes[:, 3, 0] + 1))\n )\n\n if not torch.allclose((boxes[:, 2, 1] - boxes[:, 0, 1] + 1), (boxes[:, 3, 1] - boxes[:, 1, 1] + 1)):\n raise ValueError(\n \"Boxes must have be rectangular, while get heights %s and %s\"\n % (str(boxes[:, 2, 1] - boxes[:, 0, 1] + 1), str(boxes[:, 3, 1] - boxes[:, 1, 1] + 1))\n )\n\n return True\n\n\[email protected]\ndef validate_bbox3d(boxes: torch.Tensor) -> bool:\n \"\"\"Validate if a 3D bounding box usable or not. This function checks if the boxes are cube or not.\n\n Args:\n boxes: a tensor containing the coordinates of the bounding boxes to be extracted. The tensor must have the shape\n of Bx8x3, where each box is defined in the following ``clockwise`` order: front-top-left, front-top-right,\n front-bottom-right, front-bottom-left, back-top-left, back-top-right, back-bottom-right, back-bottom-left.\n The coordinates must be in the x, y, z order.\n \"\"\"\n if not (len(boxes.shape) == 3 and boxes.shape[1:] == torch.Size([8, 3])):\n raise AssertionError(f\"Box shape must be (B, 8, 3). Got {boxes.shape}.\")\n\n left = torch.index_select(boxes, 1, torch.tensor([1, 2, 5, 6], device=boxes.device, dtype=torch.long))[:, :, 0]\n right = torch.index_select(boxes, 1, torch.tensor([0, 3, 4, 7], device=boxes.device, dtype=torch.long))[:, :, 0]\n widths = left - right + 1\n if not torch.allclose(widths.permute(1, 0), widths[:, 0]):\n raise AssertionError(f\"Boxes must have be cube, while get different widths {widths}.\")\n\n bot = torch.index_select(boxes, 1, torch.tensor([2, 3, 6, 7], device=boxes.device, dtype=torch.long))[:, :, 1]\n upper = torch.index_select(boxes, 1, torch.tensor([0, 1, 4, 5], device=boxes.device, dtype=torch.long))[:, :, 1]\n heights = bot - upper + 1\n if not torch.allclose(heights.permute(1, 0), heights[:, 0]):\n raise AssertionError(f\"Boxes must have be cube, while get different heights {heights}.\")\n\n depths = boxes[:, 4:, 2] - boxes[:, :4, 2] + 1\n if not torch.allclose(depths.permute(1, 0), depths[:, 0]):\n raise AssertionError(f\"Boxes must have be cube, while get different depths {depths}.\")\n\n return True\n\n\ndef infer_bbox_shape(boxes: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n r\"\"\"Auto-infer the output sizes for the given 2D bounding boxes.\n\n Args:\n boxes: a tensor containing the coordinates of the bounding boxes to be extracted. The tensor must have the shape\n of Bx4x2, where each box is defined in the following ``clockwise`` order: top-left, top-right, bottom-right,\n bottom-left. The coordinates must be in the x, y order.\n\n Returns:\n - Bounding box heights, shape of :math:`(B,)`.\n - Boundingbox widths, shape of :math:`(B,)`.\n\n Example:\n >>> boxes = torch.tensor([[\n ... [1., 1.],\n ... [2., 1.],\n ... [2., 2.],\n ... [1., 2.],\n ... ], [\n ... [1., 1.],\n ... [3., 1.],\n ... [3., 2.],\n ... [1., 2.],\n ... ]]) # 2x4x2\n >>> infer_bbox_shape(boxes)\n (tensor([2., 2.]), tensor([2., 3.]))\n \"\"\"\n validate_bbox(boxes)\n width: torch.Tensor = boxes[:, 1, 0] - boxes[:, 0, 0] + 1\n height: torch.Tensor = boxes[:, 2, 1] - boxes[:, 0, 1] + 1\n return height, width\n\n\ndef infer_bbox_shape3d(boxes: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n r\"\"\"Auto-infer the output sizes for the given 3D bounding boxes.\n\n Args:\n boxes: a tensor containing the coordinates of the bounding boxes to be extracted. The tensor must have the shape\n of Bx8x3, where each box is defined in the following ``clockwise`` order: front-top-left, front-top-right,\n front-bottom-right, front-bottom-left, back-top-left, back-top-right, back-bottom-right, back-bottom-left.\n The coordinates must be in the x, y, z order.\n\n Returns:\n - Bounding box depths, shape of :math:`(B,)`.\n - Bounding box heights, shape of :math:`(B,)`.\n - Bounding box widths, shape of :math:`(B,)`.\n\n Example:\n >>> boxes = torch.tensor([[[ 0, 1, 2],\n ... [10, 1, 2],\n ... [10, 21, 2],\n ... [ 0, 21, 2],\n ... [ 0, 1, 32],\n ... [10, 1, 32],\n ... [10, 21, 32],\n ... [ 0, 21, 32]],\n ... [[ 3, 4, 5],\n ... [43, 4, 5],\n ... [43, 54, 5],\n ... [ 3, 54, 5],\n ... [ 3, 4, 65],\n ... [43, 4, 65],\n ... [43, 54, 65],\n ... [ 3, 54, 65]]]) # 2x8x3\n >>> infer_bbox_shape3d(boxes)\n (tensor([31, 61]), tensor([21, 51]), tensor([11, 41]))\n \"\"\"\n validate_bbox3d(boxes)\n\n left = torch.index_select(boxes, 1, torch.tensor([1, 2, 5, 6], device=boxes.device, dtype=torch.long))[:, :, 0]\n right = torch.index_select(boxes, 1, torch.tensor([0, 3, 4, 7], device=boxes.device, dtype=torch.long))[:, :, 0]\n widths = (left - right + 1)[:, 0]\n\n bot = torch.index_select(boxes, 1, torch.tensor([2, 3, 6, 7], device=boxes.device, dtype=torch.long))[:, :, 1]\n upper = torch.index_select(boxes, 1, torch.tensor([0, 1, 4, 5], device=boxes.device, dtype=torch.long))[:, :, 1]\n heights = (bot - upper + 1)[:, 0]\n\n depths = (boxes[:, 4:, 2] - boxes[:, :4, 2] + 1)[:, 0]\n return depths, heights, widths\n\n\ndef bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:\n \"\"\"Convert 2D bounding boxes to masks. Covered area is 1. and the remaining is 0.\n\n Args:\n boxes: a tensor containing the coordinates of the bounding boxes to be extracted. The tensor must have the shape\n of Bx4x2, where each box is defined in the following ``clockwise`` order: top-left, top-right, bottom-right\n and bottom-left. The coordinates must be in the x, y order.\n width: width of the masked image.\n height: height of the masked image.\n\n Returns:\n the output mask tensor.\n\n Note:\n It is currently non-differentiable.\n\n Examples:\n >>> boxes = torch.tensor([[\n ... [1., 1.],\n ... [3., 1.],\n ... [3., 2.],\n ... [1., 2.],\n ... ]]) # 1x4x2\n >>> bbox_to_mask(boxes, 5, 5)\n tensor([[[0., 0., 0., 0., 0.],\n [0., 1., 1., 1., 0.],\n [0., 1., 1., 1., 0.],\n [0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 0.]]])\n \"\"\"\n validate_bbox(boxes)\n # zero padding the surroudings\n mask = torch.zeros((len(boxes), height + 2, width + 2))\n # push all points one pixel off\n # in order to zero-out the fully filled rows or columns\n boxes += 1\n\n mask_out = []\n # TODO: Looking for a vectorized way\n for m, box in zip(mask, boxes):\n m = m.index_fill(1, torch.arange(box[0, 0].item(), box[1, 0].item() + 1, dtype=torch.long), torch.tensor(1))\n m = m.index_fill(0, torch.arange(box[1, 1].item(), box[2, 1].item() + 1, dtype=torch.long), torch.tensor(1))\n m = m.unsqueeze(dim=0)\n m_out = (m == 1).all(dim=1) * (m == 1).all(dim=2).T\n m_out = m_out[1:-1, 1:-1]\n mask_out.append(m_out)\n\n return torch.stack(mask_out, dim=0).float()\n\n\ndef bbox_to_mask3d(boxes: torch.Tensor, size: Tuple[int, int, int]) -> torch.Tensor:\n \"\"\"Convert 3D bounding boxes to masks. Covered area is 1. and the remaining is 0.\n\n Args:\n boxes: a tensor containing the coordinates of the bounding boxes to be extracted. The tensor must have the shape\n of Bx8x3, where each box is defined in the following ``clockwise`` order: front-top-left, front-top-right,\n front-bottom-right, front-bottom-left, back-top-left, back-top-right, back-bottom-right, back-bottom-left.\n The coordinates must be in the x, y, z order.\n size: depth, height and width of the masked image.\n\n Returns:\n the output mask tensor.\n\n Examples:\n >>> boxes = torch.tensor([[\n ... [1., 1., 1.],\n ... [2., 1., 1.],\n ... [2., 2., 1.],\n ... [1., 2., 1.],\n ... [1., 1., 2.],\n ... [2., 1., 2.],\n ... [2., 2., 2.],\n ... [1., 2., 2.],\n ... ]]) # 1x8x3\n >>> bbox_to_mask3d(boxes, (4, 5, 5))\n tensor([[[[[0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 0.]],\n <BLANKLINE>\n [[0., 0., 0., 0., 0.],\n [0., 1., 1., 0., 0.],\n [0., 1., 1., 0., 0.],\n [0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 0.]],\n <BLANKLINE>\n [[0., 0., 0., 0., 0.],\n [0., 1., 1., 0., 0.],\n [0., 1., 1., 0., 0.],\n [0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 0.]],\n <BLANKLINE>\n [[0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 0.]]]]])\n \"\"\"\n validate_bbox3d(boxes)\n mask = torch.zeros((len(boxes), *size))\n\n mask_out = []\n # TODO: Looking for a vectorized way\n for m, box in zip(mask, boxes):\n m = m.index_fill(\n 0,\n torch.arange(box[0, 2].item(), box[4, 2].item() + 1, device=box.device, dtype=torch.long),\n torch.tensor(1, device=box.device, dtype=box.dtype),\n )\n m = m.index_fill(\n 1,\n torch.arange(box[1, 1].item(), box[2, 1].item() + 1, device=box.device, dtype=torch.long),\n torch.tensor(1, device=box.device, dtype=box.dtype),\n )\n m = m.index_fill(\n 2,\n torch.arange(box[0, 0].item(), box[1, 0].item() + 1, device=box.device, dtype=torch.long),\n torch.tensor(1, device=box.device, dtype=box.dtype),\n )\n m = m.unsqueeze(dim=0)\n m_out = torch.ones_like(m)\n m_out = m_out * (m == 1).all(dim=2, keepdim=True).all(dim=1, keepdim=True)\n m_out = m_out * (m == 1).all(dim=3, keepdim=True).all(dim=1, keepdim=True)\n m_out = m_out * (m == 1).all(dim=2, keepdim=True).all(dim=3, keepdim=True)\n mask_out.append(m_out)\n\n return torch.stack(mask_out, dim=0).float()\n\n\ndef bbox_generator(\n x_start: torch.Tensor, y_start: torch.Tensor, width: torch.Tensor, height: torch.Tensor\n) -> torch.Tensor:\n \"\"\"Generate 2D bounding boxes according to the provided start coords, width and height.\n\n Args:\n x_start: a tensor containing the x coordinates of the bounding boxes to be extracted. Shape must be a scalar\n tensor or :math:`(B,)`.\n y_start: a tensor containing the y coordinates of the bounding boxes to be extracted. Shape must be a scalar\n tensor or :math:`(B,)`.\n width: widths of the masked image. Shape must be a scalar tensor or :math:`(B,)`.\n height: heights of the masked image. Shape must be a scalar tensor or :math:`(B,)`.\n\n Returns:\n the bounding box tensor.\n\n Examples:\n >>> x_start = torch.tensor([0, 1])\n >>> y_start = torch.tensor([1, 0])\n >>> width = torch.tensor([5, 3])\n >>> height = torch.tensor([7, 4])\n >>> bbox_generator(x_start, y_start, width, height)\n tensor([[[0, 1],\n [4, 1],\n [4, 7],\n [0, 7]],\n <BLANKLINE>\n [[1, 0],\n [3, 0],\n [3, 3],\n [1, 3]]])\n \"\"\"\n if not (x_start.shape == y_start.shape and x_start.dim() in [0, 1]):\n raise AssertionError(f\"`x_start` and `y_start` must be a scalar or (B,). Got {x_start}, {y_start}.\")\n if not (width.shape == height.shape and width.dim() in [0, 1]):\n raise AssertionError(f\"`width` and `height` must be a scalar or (B,). Got {width}, {height}.\")\n if not x_start.dtype == y_start.dtype == width.dtype == height.dtype:\n raise AssertionError(\n \"All tensors must be in the same dtype. Got \"\n f\"`x_start`({x_start.dtype}), `y_start`({x_start.dtype}), `width`({width.dtype}), `height`({height.dtype}).\"\n )\n if not x_start.device == y_start.device == width.device == height.device:\n raise AssertionError(\n \"All tensors must be in the same device. Got \"\n f\"`x_start`({x_start.device}), `y_start`({x_start.device}), \"\n f\"`width`({width.device}), `height`({height.device}).\"\n )\n\n bbox = torch.tensor([[[0, 0], [0, 0], [0, 0], [0, 0]]], device=x_start.device, dtype=x_start.dtype).repeat(\n 1 if x_start.dim() == 0 else len(x_start), 1, 1\n )\n\n bbox[:, :, 0] += x_start.view(-1, 1)\n bbox[:, :, 1] += y_start.view(-1, 1)\n bbox[:, 1, 0] += width - 1\n bbox[:, 2, 0] += width - 1\n bbox[:, 2, 1] += height - 1\n bbox[:, 3, 1] += height - 1\n\n return bbox\n\n\ndef bbox_generator3d(\n x_start: torch.Tensor,\n y_start: torch.Tensor,\n z_start: torch.Tensor,\n width: torch.Tensor,\n height: torch.Tensor,\n depth: torch.Tensor,\n) -> torch.Tensor:\n \"\"\"Generate 3D bounding boxes according to the provided start coords, width, height and depth.\n\n Args:\n x_start: a tensor containing the x coordinates of the bounding boxes to be extracted. Shape must be a scalar\n tensor or :math:`(B,)`.\n y_start: a tensor containing the y coordinates of the bounding boxes to be extracted. Shape must be a scalar\n tensor or :math:`(B,)`.\n z_start: a tensor containing the z coordinates of the bounding boxes to be extracted. Shape must be a scalar\n tensor or :math:`(B,)`.\n width: widths of the masked image. Shape must be a scalar tensor or :math:`(B,)`.\n height: heights of the masked image. Shape must be a scalar tensor or :math:`(B,)`.\n depth: depths of the masked image. Shape must be a scalar tensor or :math:`(B,)`.\n\n Returns:\n the 3d bounding box tensor :math:`(B, 8, 3)`.\n\n Examples:\n >>> x_start = torch.tensor([0, 3])\n >>> y_start = torch.tensor([1, 4])\n >>> z_start = torch.tensor([2, 5])\n >>> width = torch.tensor([10, 40])\n >>> height = torch.tensor([20, 50])\n >>> depth = torch.tensor([30, 60])\n >>> bbox_generator3d(x_start, y_start, z_start, width, height, depth)\n tensor([[[ 0, 1, 2],\n [10, 1, 2],\n [10, 21, 2],\n [ 0, 21, 2],\n [ 0, 1, 32],\n [10, 1, 32],\n [10, 21, 32],\n [ 0, 21, 32]],\n <BLANKLINE>\n [[ 3, 4, 5],\n [43, 4, 5],\n [43, 54, 5],\n [ 3, 54, 5],\n [ 3, 4, 65],\n [43, 4, 65],\n [43, 54, 65],\n [ 3, 54, 65]]])\n \"\"\"\n if not (x_start.shape == y_start.shape == z_start.shape and x_start.dim() in [0, 1]):\n raise AssertionError(\n f\"`x_start`, `y_start` and `z_start` must be a scalar or (B,). Got {x_start}, {y_start}, {z_start}.\"\n )\n if not (width.shape == height.shape == depth.shape and width.dim() in [0, 1]):\n raise AssertionError(f\"`width`, `height` and `depth` must be a scalar or (B,). Got {width}, {height}, {depth}.\")\n if not x_start.dtype == y_start.dtype == z_start.dtype == width.dtype == height.dtype == depth.dtype:\n raise AssertionError(\n \"All tensors must be in the same dtype. \"\n f\"Got `x_start`({x_start.dtype}), `y_start`({x_start.dtype}), `z_start`({x_start.dtype}), \"\n f\"`width`({width.dtype}), `height`({height.dtype}) and `depth`({depth.dtype}).\"\n )\n if not x_start.device == y_start.device == z_start.device == width.device == height.device == depth.device:\n raise AssertionError(\n \"All tensors must be in the same device. \"\n f\"Got `x_start`({x_start.device}), `y_start`({x_start.device}), `z_start`({x_start.device}), \"\n f\"`width`({width.device}), `height`({height.device}) and `depth`({depth.device}).\"\n )\n\n # front\n bbox = torch.tensor(\n [[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]], device=x_start.device, dtype=x_start.dtype\n ).repeat(len(x_start), 1, 1)\n\n bbox[:, :, 0] += x_start.view(-1, 1)\n bbox[:, :, 1] += y_start.view(-1, 1)\n bbox[:, :, 2] += z_start.view(-1, 1)\n bbox[:, 1, 0] += width\n bbox[:, 2, 0] += width\n bbox[:, 2, 1] += height\n bbox[:, 3, 1] += height\n\n # back\n bbox_back = bbox.clone()\n bbox_back[:, :, -1] += depth.unsqueeze(dim=1).repeat(1, 4)\n bbox = torch.cat([bbox, bbox_back], dim=1)\n\n return bbox\n\n\ndef transform_bbox(trans_mat: torch.Tensor, boxes: torch.Tensor, mode: str = \"xyxy\") -> torch.Tensor:\n r\"\"\"Function that applies a transformation matrix to a box or batch of boxes. Boxes must\n be a tensor of the shape (N, 4) or a batch of boxes (B, N, 4) and trans_mat must be a (3, 3)\n transformation matrix or a batch of transformation matrices (B, 3, 3)\n\n Args:\n trans_mat: The transformation matrix to be applied\n boxes: The boxes to be transformed\n mode: The format in which the boxes are provided. If set to 'xyxy' the boxes are assumed to be in the format\n ``xmin, ymin, xmax, ymax``. If set to 'xywh' the boxes are assumed to be in the format\n ``xmin, ymin, width, height``\n Returns:\n The set of transformed points in the specified mode\n\n\n \"\"\"\n if not isinstance(mode, str):\n raise TypeError(f\"Mode must be a string. Got {type(mode)}\")\n\n if mode not in (\"xyxy\", \"xywh\"):\n raise ValueError(f\"Mode must be one of 'xyxy', 'xywh'. Got {mode}\")\n\n # convert boxes to format xyxy\n if mode == \"xywh\":\n boxes[..., -2] = boxes[..., 0] + boxes[..., -2] # x + w\n boxes[..., -1] = boxes[..., 1] + boxes[..., -1] # y + h\n\n transformed_boxes: torch.Tensor = kornia.transform_points(trans_mat, boxes.view(boxes.shape[0], -1, 2))\n transformed_boxes = transformed_boxes.view_as(boxes)\n\n if mode == 'xywh':\n transformed_boxes[..., 2] = transformed_boxes[..., 2] - transformed_boxes[..., 0]\n transformed_boxes[..., 3] = transformed_boxes[..., 3] - transformed_boxes[..., 1]\n\n return transformed_boxes\n"
] | [
[
"torch.ones_like",
"torch.stack",
"torch.Size",
"torch.tensor",
"torch.cat",
"torch.allclose"
]
] |
kshitijsriv/Computer-Vision-Spring-19 | [
"7e84726d51d30ecf8a22e890aced5a48e3b5b7e5"
] | [
"Assignments/Assignment-4/Code/Question_4/panorama.py"
] | [
"# ref: https://pylessons.com/OpenCV-image-stiching-continue/\n\nimport cv2\nimport numpy as np\n\nimg_ = cv2.imread('1a.jpg')\n# img_ = cv2.resize(img_, (0,0), fx=1, fy=1)\nimg1 = cv2.cvtColor(img_, cv2.COLOR_BGR2GRAY)\n\nimg = cv2.imread('1b.jpg')\n# img = cv2.resize(img, (0,0), fx=1, fy=1)\nimg2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\nmin_shape = img2.shape\nprint(img1.shape, img2.shape, min_shape)\nimg1 = cv2.resize(img1, (min_shape[1], min_shape[0]))\nprint(img1.shape)\n\nsift = cv2.xfeatures2d.SIFT_create()\n# find the key points and descriptors with SIFT\nkp1, des1 = sift.detectAndCompute(img1, None)\nkp2, des2 = sift.detectAndCompute(img2, None)\ncv2.imshow('img_keypoints', cv2.drawKeypoints(img_, kp1, None))\n\nmatch = cv2.BFMatcher()\nmatches = match.knnMatch(des1, des2, k=2)\n\ngood = []\nfor m, n in matches:\n if m.distance < 0.5 * n.distance:\n good.append(m)\n\ndraw_params = dict(matchColor=(0, 255, 0), # draw matches in green color\n singlePointColor=None,\n flags=2)\n\nimg3 = cv2.drawMatches(img_, kp1, img, kp2, good, None, **draw_params)\ncv2.imshow(\"matched.jpg\", img3)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\nMIN_MATCH_COUNT = 10\nif len(good) > MIN_MATCH_COUNT:\n src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)\n dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)\n M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)\n h, w = img1.shape\n pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)\n dst = cv2.perspectiveTransform(pts, M)\n img2 = cv2.polylines(img2, [np.int32(dst)], True, 255, 3, cv2.LINE_AA)\n cv2.imshow(\"original_image_overlapping.jpg\", img2)\nelse:\n print(\"Not enough matches are found - %d/%d\", (len(good) / MIN_MATCH_COUNT))\n\ndst = cv2.warpPerspective(img_, M, (img.shape[1] + img_.shape[1], img.shape[0]))\ndst[0:img.shape[0], 0:img.shape[1]] = img\n\nprint(\"DST\", dst.shape)\ncv2.imshow(\"original_image_stitched.jpg\", dst)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n# cv2.imsave(\"original_image_stitched_crop.jpg\")\n"
] | [
[
"numpy.int32",
"numpy.float32"
]
] |
bayartsogt-ya/TransformerTTS | [
"2f3a1b580515a8b33a624bcdf163e549916065d6"
] | [
"create_dataset.py"
] | [
"import argparse\nimport os\nfrom pathlib import Path\n\nimport librosa\nimport numpy as np\nimport tqdm\nimport ruamel.yaml\n\nfrom preprocessing.text_processing import Phonemizer, TextCleaner\nfrom utils.audio import melspectrogram\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--config', dest='CONFIG', type=str, required=True)\nparser.add_argument('--dont_cache_phonemes', dest='CACHE_PHON', action='store_false')\nparser.add_argument('--njobs', dest='NJOBS', type=int, default=16)\nparser.add_argument('--col_sep', dest='COLUMN_SEP', type=str, default='|')\nparser.add_argument('--recompute_phon', dest='RECOMPUTE_PHON', action='store_true')\nargs = parser.parse_args()\nfor arg in vars(args):\n print('{}: {}'.format(arg, getattr(args, arg)))\nyaml = ruamel.yaml.YAML()\nconfig = yaml.load(open(str(Path(args.CONFIG) / 'data_config.yaml'), 'rb'))\nargs.DATA_DIR = config['data_directory']\nargs.META_FILE = os.path.join(args.DATA_DIR, config['metadata_filename'])\nargs.WAV_DIR = os.path.join(args.DATA_DIR, config['wav_subdir_name'])\nargs.TARGET_DIR = config['train_data_directory']\nif args.TARGET_DIR is None:\n args.TARGET_DIR = args.DATA_DIR\n\nmel_dir = os.path.join(args.TARGET_DIR, 'mels')\nif not os.path.exists(mel_dir):\n os.makedirs(mel_dir)\n\nphon_path = os.path.join(args.TARGET_DIR, 'phonemes.npy')\nif os.path.exists(phon_path) and not args.RECOMPUTE_PHON:\n print(\"using cached phonemes\")\n audio_data = np.load(phon_path)\nelse:\n print('\\nLoading and cleaning text')\n text_cleaner = TextCleaner()\n audio_data = []\n with open(args.META_FILE, 'r', encoding='utf-8') as f:\n for l in f.readlines():\n l_split = l.split(args.COLUMN_SEP)\n filename, text = l_split[0], l_split[-1]\n if filename.endswith('.wav'):\n filename = filename.split('.')[-1]\n text = text_cleaner.clean(text)\n audio_data.append((filename, text))\n audio_data = np.array(audio_data)\n print('\\nPhonemizing')\n \n phonemizer = Phonemizer(config['phoneme_language'])\n texts = audio_data[:, 1]\n batch_size = 250 # batch phonemization to avoid memory issues.\n phonemes = []\n for i in tqdm.tqdm(range(0, len(audio_data), batch_size)):\n batch = texts[i: i + batch_size]\n batch = phonemizer.encode(batch, njobs=args.NJOBS, clean=False)\n phonemes.extend(batch)\n audio_data = np.concatenate([np.array(audio_data), np.expand_dims(phonemes, axis=1)], axis=1)\n if args.CACHE_PHON:\n np.save(phon_path, audio_data, allow_pickle=True)\n\nprint('\\nBuilding dataset and writing files')\nnp.random.seed(42)\nnp.random.shuffle(audio_data)\ntest_metafile = os.path.join(args.TARGET_DIR, 'test_metafile.txt')\ntrain_metafile = os.path.join(args.TARGET_DIR, 'train_metafile.txt')\n\ntest_lines = [''.join([filename, '|', text, '|', phon, '\\n']) for filename, text, phon in\n audio_data[:config['n_test']]]\ntrain_lines = [''.join([filename, '|', text, '|', phon, '\\n']) for filename, text, phon in\n audio_data[config['n_test']:-1]]\n\nwith open(test_metafile, 'w+', encoding='utf-8') as test_f:\n test_f.writelines(test_lines)\nwith open(train_metafile, 'w+', encoding='utf-8') as train_f:\n train_f.writelines(train_lines)\n\nfor i in tqdm.tqdm(range(len(audio_data))):\n filename, _, _ = audio_data[i]\n wav_path = os.path.join(args.WAV_DIR, filename + '.wav')\n y, sr = librosa.load(wav_path, sr=config['sampling_rate'])\n mel = melspectrogram(y, config)\n mel_path = os.path.join(mel_dir, filename)\n np.save(mel_path, mel.T)\nprint('\\nDone')\n"
] | [
[
"numpy.load",
"numpy.save",
"numpy.random.shuffle",
"numpy.random.seed",
"numpy.expand_dims",
"numpy.array"
]
] |
jnduli/edx_anaconda_machine_learning | [
"5eb1d967c0bbff545baf86860a6bd4074840747f"
] | [
"scatterplot.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 8 12:40:35 2016\n\n@author: rookie\n\"\"\"\n\nimport pandas as pd\nimport matplotlib as mpl\n\nmpl.style.use('ggplot')\n\nstudent_dataset = pd.read_csv(\"students.data\",index_col=0)\nstudent_dataset.plot.scatter(x='G1', y='G3')\n"
] | [
[
"pandas.read_csv",
"matplotlib.style.use"
]
] |
ivmfnal/python_model | [
"37be0df7d58b5ad25df8d4d4cabe77129d405b05"
] | [
"python_model.py"
] | [
"import numpy as np\nimport json\n\ndef softmax(x):\n x = x - np.max(x, axis=-1, keepdims=True)\n expx = np.exp(x)\n return expx/np.sum(expx, axis=-1, keepdims=True)\n\ndef sigmoid(x):\n return 1.0/(1.0 + np.exp(-x))\n \ndef tanh(x):\n return sigmoid(2*x)*2-1\n \ndef relu(x):\n return (x+np.abs(x))/2 \n\nactivations = {\n \"tanh\": tanh,\n \"sigmoid\": sigmoid,\n \"softmax\": softmax,\n \"relu\": relu\n}\n\nclass Dense(object):\n \n NWeights = 2\n \n def __init__(self, in_width, out_width, activation=\"softmax\"):\n self.InWidth = in_width\n self.OutWidth = out_width\n self.W = None\n self.B = None\n self.Activation = activations[activation]\n\n def set_weights(self, w, b):\n self.W = w\n self.B = b\n \n def compute(self, x):\n return self.Activation(np.dot(x, self.W) + self.B)\n\nclass LSTM(object):\n\n NWeights = 3\n \n def __init__(self, in_width, out_width, return_sequences=False, activation=\"tanh\"):\n self.InWidth = in_width\n self.OutWidth = out_width\n self.XW = None\n self.SW = None\n self.B = None\n self.ReturnSequences = False\n self.Activation = activations[activation]\n \n def set_weights(self, xw, sw, b):\n self.XW = xw\n self.SW = sw\n self.B = b\n \n def compute(self, batch):\n # batch: (mb_size, time_length, in_width)\n mb_size, time_length, in_width = batch.shape\n assert in_width == self.InWidth\n state_c = np.zeros((mb_size, self.OutWidth))\n state_h = np.zeros((mb_size, self.OutWidth))\n Y = np.empty((mb_size, time_length, self.OutWidth))\n for t in range(time_length):\n xt = batch[:,t,:]\n z = np.dot(state_h, self.SW) + np.dot(xt, self.XW) + self.B\n f = sigmoid(z[:,self.OutWidth:self.OutWidth*2])\n I = sigmoid(z[:,:self.OutWidth])\n c = np.tanh(z[:,self.OutWidth*2:self.OutWidth*3])\n o = sigmoid(z[:,self.OutWidth*3:])\n \n state_c = state_c*f + I*c\n state_h = self.Activation(state_c)*o\n \n Y[:,t,:] = state_h\n if self.ReturnSequences:\n return Y\n else:\n return Y[:,-1,:]\n\nclass Model(object):\n \n def __init__(self, layers):\n self.Layers = layers\n \n def set_weights(self, weights):\n for l in self.Layers:\n n = l.NWeights\n l.set_weights(*weights[:n])\n weights = weights[n:]\n\n def compute(self, x):\n for l in self.Layers:\n x = l.compute(x)\n return x\n \n @staticmethod\n def save_keras_model(model, file_prefix):\n open(file_prefix+\"_desc.json\", \"w\").write(model.to_json())\n np.savez(file_prefix+\"_weights.npz\", *model.get_weights())\n\n @staticmethod\n def from_saved(file_prefix):\n desc = json.load(open(file_prefix+\"_desc.json\", \"r\"))\n weights = np.load(file_prefix+\"_weights.npz\")\n weights = [weights[name] for name in weights.files]\n return Model.create_from_desc_and_weights(desc, weights)\n \n @staticmethod\n def create_from_desc_and_weights(desc, weights):\n if isinstance(desc, str):\n desc = json.loads(desc)\n layers = []\n config = desc[\"config\"]\n shape = None\n for ldesc in config[\"layers\"]:\n cname = ldesc[\"class_name\"]\n lcfg = ldesc[\"config\"]\n if cname == \"InputLayer\":\n shape = lcfg[\"batch_input_shape\"]\n elif cname == \"LSTM\":\n width = lcfg[\"units\"]\n activation = lcfg[\"activation\"]\n sequences = lcfg[\"return_sequences\"]\n layers.append(LSTM(shape[-1], width, activation=activation, return_sequences=sequences))\n shape = (shape[0], width) if not sequences else (shape[0], shape[1], width)\n elif cname == \"Dense\":\n width = lcfg[\"units\"]\n activation = lcfg[\"activation\"]\n layers.append(Dense(shape[-1], width, activation=activation))\n shape = [width]\n\n model = Model(layers)\n model.set_weights(weights)\n return model\n \n\n "
] | [
[
"numpy.sum",
"numpy.load",
"numpy.empty",
"numpy.zeros",
"numpy.abs",
"numpy.exp",
"numpy.max",
"numpy.dot",
"numpy.tanh"
]
] |
TARTRL/RankingCost | [
"4ac7faebf006d1143b98a6eada651bcab6ec5063"
] | [
"gridworld/algorithms/ranking_cost/show_weight.py"
] | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Copyright 2021 The TARTRL Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\n\nimport pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef save_cost_maps(save_dir, name, weight):\n heat_maps = weight[1]\n\n for h_i, heat_map in enumerate(heat_maps):\n fig, ax = plt.subplots(1, 1, figsize=(15, 15))\n\n\n im = ax.imshow(heat_map)\n cbar = ax.figure.colorbar(im, ax=ax, cmap=\"YlGn\")\n cbar.ax.set_ylabel('color bar', rotation=-90, va=\"bottom\")\n for edge, spine in ax.spines.items():\n spine.set_visible(False)\n ax.set_xticks(np.arange(heat_map.shape[1] + 1) - .5, minor=True)\n ax.set_yticks(np.arange(heat_map.shape[0] + 1) - .5, minor=True)\n ax.grid(which=\"minor\", color=\"w\", linestyle='-', linewidth=1)\n ax.tick_params(which=\"minor\", bottom=False, left=False)\n\n for i in range(heat_map.shape[0]):\n for j in range(heat_map.shape[1]):\n\n text = ax.text(j, i, '{:.1f}'.format(heat_map[i, j]),\n ha=\"center\", va=\"center\", color=\"w\", fontsize=60)\n\n fig.tight_layout()\n save_path = os.path.join(save_dir, '{}_{}.png'.format(name, h_i))\n print('save cost map to:',save_path)\n plt.savefig(save_path)\n\n\ndef save_cost_maps_v0(save_dir, name, weight):\n heat_maps = np.maximum(weight[1], 0) * 10\n\n for h_i, heat_map in enumerate(heat_maps):\n fig, ax = plt.subplots(1, 1, figsize=(15, 15))\n im = ax.imshow(heat_map)\n cbar = ax.figure.colorbar(im, ax=ax, cmap=\"YlGn\")\n cbar.ax.set_ylabel('color bar', rotation=-90, va=\"bottom\")\n for edge, spine in ax.spines.items():\n spine.set_visible(False)\n ax.set_xticks(np.arange(heat_map.shape[1] + 1) - .5, minor=True)\n ax.set_yticks(np.arange(heat_map.shape[0] + 1) - .5, minor=True)\n ax.grid(which=\"minor\", color=\"w\", linestyle='-', linewidth=1)\n ax.tick_params(which=\"minor\", bottom=False, left=False)\n\n for i in range(heat_map.shape[0]):\n for j in range(heat_map.shape[1]):\n\n text = ax.text(j, i, int(heat_map[i, j]),\n ha=\"center\", va=\"center\", color=\"w\", fontsize=60)\n\n fig.tight_layout()\n save_path = os.path.join(save_dir, '{}_{}.png'.format(name, h_i))\n plt.savefig(save_path)\n\ndef load_weight():\n weight_file = './images/solver_map02_0_True_VonNeumann.pkl'\n with open(weight_file, 'rb') as f:\n weights = pickle.load(f)\n\n heat_maps = np.maximum(weights[1], 0) * 10\n map_index = 0\n for heat_map in heat_maps:\n fig, ax = plt.subplots(1, 1, figsize=(15, 15))\n\n im = ax.imshow(heat_map)\n cbar = ax.figure.colorbar(im, ax=ax, cmap=\"YlGn\")\n cbar.ax.set_ylabel('color bar', rotation=-90, va=\"bottom\")\n for edge, spine in ax.spines.items():\n spine.set_visible(False)\n ax.set_xticks(np.arange(heat_map.shape[1] + 1) - .5, minor=True)\n ax.set_yticks(np.arange(heat_map.shape[0] + 1) - .5, minor=True)\n ax.grid(which=\"minor\", color=\"w\", linestyle='-', linewidth=1)\n ax.tick_params(which=\"minor\", bottom=False, left=False)\n\n for i in range(heat_map.shape[0]):\n for j in range(heat_map.shape[1]):\n # print(i,j)\n text = ax.text(j, i, int(heat_map[i, j]),\n ha=\"center\", va=\"center\", color=\"w\")\n ax.set_title(\"heat map\")\n fig.tight_layout()\n plt.savefig('./images/heat_maps/{}.png'.format(map_index))\n map_index += 1\n\n\nif __name__ == '__main__':\n load_weight()\n"
] | [
[
"numpy.maximum",
"matplotlib.pyplot.savefig",
"numpy.arange",
"matplotlib.pyplot.subplots"
]
] |
dkllrjr/PyKeller | [
"6788876a0ab273c19e1643d7bce637f6e700eb99"
] | [
"build/lib/atmos_sci/mplnet.py"
] | [
"#NASA MPLNET functions\n\nimport numpy as np\nimport os\nos.chdir('..')\nos.chdir('..')\nimport PyKeller.signal_processing.pycuda_wavelets as py_wv\nimport PyKeller.signal_processing.wavelets as wv\nimport PyKeller.signal_processing.signal_analysis as sa\nimport PyKeller.atmos_sci.met_analysis as ma\nimport matplotlib.pyplot as plt\nfrom scipy import signal\n\ndef nrb_pad(nrb,z):\n nrb_padded = []\n for i in range(nrb[0,:].size):\n nrb_new,z_new = wv.padding_start_sg(nrb[:,i],z,337.4741,0.01,5) #337.4741 m is the height of the mpl above sea level\n nrb_padded.append(nrb_new)\n nrb_padded = np.transpose(np.array(nrb_padded))\n z_padded = z_new\n return nrb_padded,z_padded\n\ndef cuda_pbl_layers(nrb,z):\n res = z[1]-z[0]\n a = np.arange(4*res,z[18]+res,res) #change to an end point of about 4 km if the height array is limited\n if np.isnan(nrb[0]): #checking for nan filled nrb files\n return []\n wt = py_wv.kwwt(nrb,z,a,z,5)\n wt = wt.real\n wt = wv.clip_wavelet_kw(wt,a,z)\n pblh = pbl_layer(wt,z)\n return pblh\n \ndef pbl_layers(wt,b):\n wt = sa.moving_mean(wt[0,:],1)\n pks,_ = signal.find_peaks(wt)\n pks,_ = signal.find_peaks(wt,height=np.mean(wt[pks]))\n return pks\n \ndef pbl_layer(wt,b): #Just takes the max, seems to work really well\n wt = sa.moving_mean(wt[0,:],1)\n pks = np.where(wt==np.nanmax(wt))[0]\n if len(pks) > 0:\n return list(pks)\n else:\n return []\n\ndef pbl_layers_heights(pblh,z):\n k = 0\n for i in range(len(pblh)):\n if len(pblh[i]) > k:\n k = len(pblh[i])\n layers = np.empty((len(pblh),k))\n layers.fill(np.nan)\n for i in range(len(pblh)):\n for j in range(k):\n if j < len(pblh[i]):\n if not np.isnan(pblh[i][j]):\n layers[i,j] = z[pblh[i][j]]\n return layers\n\ndef run_pbl_layers(nrb,z):\n z = z[0:46]\n nrb = nrb[0:46,:]\n nrb,z = nrb_pad(nrb,z)\n pblh = []\n for i in range(nrb[0,:].size):\n nrb_i = sa.moving_mean(nrb[:,i],1)\n pblh.append(cuda_pbl_layers(nrb_i,z))\n return nrb,z,pblh\n\ndef plot_nrb(nrb,z,t,t_div):\n st = ma.min_to_hour_min(t)\n plt.style.use('dark_background')\n plt.pcolormesh(t,z,nrb,cmap='gnuplot2',vmin=0,vmax=2,zorder=1)\n plt.xticks(t[0:t.size:t_div],st[0:t.size:t_div], rotation='vertical')\n plt.show()\n \ndef plot_nrb_layers(nrb,z,t,t_div,layers):\n for i in range(len(layers[0])):\n plt.scatter(t,layers[:,i],zorder=2)\n plot_nrb(nrb,z,t,t_div)"
] | [
[
"matplotlib.pyplot.style.use",
"matplotlib.pyplot.pcolormesh",
"numpy.nanmax",
"numpy.mean",
"matplotlib.pyplot.xticks",
"numpy.arange",
"scipy.signal.find_peaks",
"matplotlib.pyplot.show",
"numpy.isnan",
"numpy.array",
"matplotlib.pyplot.scatter"
]
] |
aadityasinha-dotcom/autoai | [
"600934c172f3c7f8bf8aa17fcc5b877d6bd628e3"
] | [
"blobcity/utils/AutoFeatureSelection.py"
] | [
"# Copyright 2021 BlobCity, Inc\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nThis Python File Consists of Functions to perform Automatic feature Selection \n\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.feature_selection import VarianceThreshold,SelectKBest,f_regression,f_classif\nfrom sklearn.preprocessing import MinMaxScaler\nfrom statistics import mean\nfrom blobcity.utils.Cleaner import dataCleaner\nclass AutoFeatureSelection: \n\n def dropHighCorrelationFeatures(X):\n \"\"\"\n param1: pandas DataFrame\n\n return: pandas DataFrame\n\n Function calculates Mutual Correlation of the passed dataframe,\n and drop one of the feature which are highly correlated to each other,\n \"\"\"\n cor_matrix = X.corr()\n upper_tri = cor_matrix.where(np.triu(np.ones(cor_matrix.shape),k=1).astype(np.bool))\n to_drop = [column for column in upper_tri.columns if any(upper_tri[column] > 0.95)]\n if to_drop!=[]:\n return X.drop(to_drop, axis=1)\n else:\n return X\n\n def dropConstantFeatures(X):\n \"\"\"\n param1: pandas DataFrame\n return: pandas DataFrame\n \n Funciton drops column with low variance/constant values in the field.\n VarianceThreshold function is utilized to filter out such columns from the DataFrame\n and once all such columns are dropped if exists return the dataframe.\n \"\"\"\n cols=X.columns\n constant_filter = VarianceThreshold(threshold=0).fit(X)\n constcols=[col for col in cols if col not in cols[constant_filter.get_support()]]\n if(constcols!=[]): X.drop(constcols,axis=1,inplace=True)\n return X\n\n def MainScore(resultscore,dc):\n\n \"\"\"\n param1: dictionary - feature importance scores \n param2: Class Object - Dictionary class\n\n return: dictionary \n\n Function calculate and filter dictionary on the basis on the existence of Categorical feature(String type features).\n first the function check whether the dataset had any String categorical feature using previously stored Boolean Class variable .\n If String Categorical feature exist return aggregate score for the actually features and return it.\n else return passed feature score.\n \"\"\"\n #average on categorical features\n if(dc.ObjectExist):\n objList=dc.ObjectList\n for i in objList:\n resultscore[i]=mean(list(dict(filter(lambda item: i in item[0], resultscore.items())).values()))\n #resulting dictionary \n res = dict()\n for key, val in resultscore.items():\n if not any(ele+\"_\" in key for ele in objList): res[key] = val\n return res\n else: return resultscore\n\n #feature importance calculator\n def get_feature_importance(X,Y,score_func,dc):\n \"\"\"\n param1: pandas DataFrame X Features\n param2: pandas Series/Dataframe target dataset\n param3: Sklearn.feature_selection function \n param4: Class Object of Dictionary Class\n\n return: pandas DataFrame\n\n Working:\n\n Function Selects Feature on the basis of feature importance using f_classif or f_regression function.\n Feature importance score generated using SelectKBest Function is then Scaled in range of 0 to 1, using MinMaxScaler function\n To manage feature from one hot encoding if any categorical feature exists MainScore function returns an average/mean score for the appropirate feature.\n if the dataframe has less then equal to 2 features return orignal dataframe. else return a short listed dataframe on the basis of \n categorical features.\n \"\"\"\n if(X.shape[1]<3):\n return X\n else:\n fit = SelectKBest(score_func=score_func, k=X.shape[1]).fit(X,Y)\n dfscores,dfcolumns = pd.DataFrame(fit.scores_),pd.DataFrame(X.columns)\n df = pd.concat([dfcolumns,dfscores],axis=1)\n df.columns = ['features','Score'] \n df['Score']=MinMaxScaler().fit_transform(np.array(df['Score']).reshape(-1,1))\n imp=AutoFeatureSelection.MainScore(dict(df.values),dc)\n return AutoFeatureSelection.GetAbsoluteList(imp,X,dict(df.values))\n \n def GetAbsoluteList(resdic,dataframe,impmain):\n\n \"\"\"\n param1: Dictionary\n param2: pandas.DataFrame\n param3: Dictionary\n\n return: pandas.DataFrame\n \"\"\"\n for key, value in resdic.items():\n if value < 0.01 and key in dataframe.columns.to_list(): \n keylist=[key2 for key2, value2 in impmain.items() if key in key2]\n dataframe.drop(keylist,axis=1,inplace=True)\n return dataframe\n\n def FeatureSelection(dataframe,target,dc):\n \"\"\"\n param1: pandas DataFrame\n param2: target column name\n param3: Class object\n \n return : pandas dataframe\n\n Function starting with performing data cleaning process of the data by calling dataCleaner funciton.\n On the Basis of problem type either Classification or Regression assigns scoring function for feature selection.\n perform a subset for feature set and target set.\n Pass the Feature set/independent features through feature selection process has follow:\n 1. Droping Constant Features\n 2. Droping Highly Correlated features\n 3. Droping Columns on basis of Feature Importance Criteria.\n and finally return List of features to utilize ahead for processing and model training.\n \"\"\"\n df=dataCleaner(dataframe,dataframe.drop(target,axis=1).columns.to_list(),target,dc)\n if(dc.getdict()['problem'][\"type\"]=='Classification'):score_func=f_classif \n else: score_func=f_regression\n \n X=df.drop(target,axis=1)\n Y=df[target]\n \n X=AutoFeatureSelection.dropConstantFeatures(X)\n X=AutoFeatureSelection.dropHighCorrelationFeatures(X)\n X=AutoFeatureSelection.get_feature_importance(X,Y,score_func,dc)\n featureList=AutoFeatureSelection.getOriginalFeatures(X.columns.to_list(),dc)\n dc.addKeyValue('features',{'X_values':featureList,'Y_values':target})\n return featureList\n\n def getOriginalFeatures(featureList,dc):\n \"\"\"\n param1: List\n param2: Class object\n \n return: List\n\n Function check whether Object type data exists using Class Variable.\n if exists shorts/filters list of feature on the basis of feature importance list.\n and return filtered List of features\n \"\"\"\n if(dc.ObjectExist):\n res,res2= [],[]#List\n for val in featureList: #filter for String categorical field existence.\n if not any(ele+\"_\" in val for ele in dc.ObjectList): res.append(val)\n res=res+dc.ObjectList\n for v in res:# filter for Selected String categorical\n if not any (v in ele for ele in featureList): res2.append(v)\n # filter to consider the features\n res3=[i for i in res if i not in res2]\n return res3 \n else: return featureList"
] | [
[
"numpy.ones",
"sklearn.preprocessing.MinMaxScaler",
"pandas.DataFrame",
"pandas.concat",
"sklearn.feature_selection.SelectKBest",
"sklearn.feature_selection.VarianceThreshold",
"numpy.array"
]
] |
shantanu-garg/Data_Science_Projects | [
"2c4287dff9e624644ce4c8dc520b83c74a6555ee"
] | [
"Gender_Classifier.py"
] | [
"from sklearn import tree\nfrom sklearn import ensemble\nfrom sklearn import neighbors\nfrom sklearn import neural_network\n\n\n#X = [height, weight, shoe size]\n\nX = [[190,80,10],[132,45,6],[189,67,9],[202,100,13],[145,67,6],[154,45,8],[148,89,9],[159,90,7],[188,78,12],[163,80,8]]\nY =['Female','Male','Male','Male','Female','Female','Male','Female','Female','Male']\n\n# Classifying using Decision Trees\nclf = tree.DecisionTreeClassifier()\n\nclf = clf.fit(X,Y)\n\nprediction = clf.predict([[190,56,8]])\n\nprint(\"Decision tree Result:\",prediction)\n\n#Classification using Random Forest\n\nclf2 = ensemble.RandomForestClassifier()\n\nclf2 = clf2.fit(X,Y)\nprediction2 = clf2.predict([[190,56,8]])\nprint(\"Random Forest Result:\",prediction2)\n\n#Classification using KNN\n\nclf3 = neighbors.KNeighborsClassifier()\nclf3 = clf3.fit(X,Y)\n\nprediction3 = clf3.predict([[190,56,8]])\nprint(\"KNN Result:\",prediction3)\n\n#Classification using neural network\n\nclf4 = neural_network.MLPClassifier()\nclf4 = clf4.fit(X,Y)\n\nprediction4 = clf4.predict([[190,56,8]])\nprint(\"Neural Network Result:\",prediction4)\n\n"
] | [
[
"sklearn.tree.DecisionTreeClassifier",
"sklearn.neighbors.KNeighborsClassifier",
"sklearn.neural_network.MLPClassifier",
"sklearn.ensemble.RandomForestClassifier"
]
] |
io8ex/Stone-Soup | [
"071abc8f6004296ab35094db04c7ec410103c419"
] | [
"stonesoup/smoother/kalman.py"
] | [
"# -*- coding: utf-8 -*-\nimport copy\nfrom functools import partial\n\nimport numpy as np\n\nfrom .base import Smoother\nfrom ..base import Property\nfrom ..types.multihypothesis import MultipleHypothesis\nfrom ..types.prediction import Prediction, GaussianStatePrediction\nfrom ..types.update import Update, GaussianStateUpdate\nfrom ..models.base import LinearModel\nfrom ..models.transition.base import TransitionModel\nfrom ..models.transition.linear import LinearGaussianTransitionModel\nfrom ..functions import gauss2sigma, unscented_transform\n\n\nclass KalmanSmoother(Smoother):\n r\"\"\"\n The linear-Gaussian or Rauch-Tung-Striebel smoother, colloquially the Kalman smoother [1]_. The\n transition model is therefore linear-Gaussian. No control model is currently implemented.\n\n TODO: Include a control model\n\n The smooth function undertakes the backward algorithm on a :class:`~.Track()` object. This is\n done by starting at the final index in the track, :math:`K` and proceeding from\n :math:`K \\rightarrow 1` via:\n\n .. math::\n\n \\mathbf{x}_{k|k-1} &= F_{k} \\mathbf{x}_{k-1}\n\n P_{k|k-1} &= F_{k} P_{k-1} F_{k}^T + Q_{k}\n\n G_k &= P_{k-1} F_{k}^T P_{k|k-1}^{-1}\n\n \\mathbf{x}_{k-1}^s &= \\mathbf{x}_{k-1} + G_k (\\mathbf{x}_{k}^s - \\mathbf{x}_{k|k-1})\n\n P_{k-1}^s &= P_{k-1} + G_k (P_{k}^s - P_{k|k-1}) G_k^T\n\n where :math:`\\mathbf{x}_{K}^s = \\mathbf{x}_{K}` and :math:`P_K^s = P_K`.\n\n The predicted state vector and covariance are retrieved from the Track via predicted state or\n updated state via the links therein. Note that this means that the first two equations are not\n calculated, the results merely retrieved. This smoother is therefore strictly Kalman only in\n the backward portion. The prediction might have come by any number of means. If present, the\n transition model (providing :math:`F` and :math:`Q`) in the prediction is used. This allows for\n a dynamic transition model (i.e. one that changes with :math:`k`). Otherwise, the (static)\n transition model is used, defined on smoother initialisation.\n\n References\n\n .. [1] Särkä S. 2013, Bayesian filtering and smoothing, Cambridge University Press\n\n \"\"\"\n\n transition_model: LinearGaussianTransitionModel = Property(\n doc=\"The transition model. The :meth:`smooth` function will initially look for a \"\n \"transition model in the prediction. If that is not found then this one is used.\")\n\n def _prediction(self, state):\n \"\"\" Return the predicted state, either from the prediction directly, or from the attached\n hypothesis if the queried state is an Update. If not a :class:`~.GaussianStatePrediction`\n or :class:`~.GaussianStateUpdate` a :class:`~.TypeError` is thrown.\n\n Parameters\n ----------\n state : :class:`~.GaussianStatePrediction` or :class:`~.GaussianStateUpdate`\n\n Returns\n -------\n : :class:`~.GaussianStatePrediction`\n The prediction associated with the prediction (i.e. itself), or the prediction from the\n hypothesis used to generate an update.\n \"\"\"\n if isinstance(state, GaussianStatePrediction):\n return state\n elif isinstance(state, GaussianStateUpdate):\n if isinstance(state.hypothesis, MultipleHypothesis):\n predictions = {hypothesis.prediction for hypothesis in state.hypothesis}\n if len(predictions) == 1:\n # One predictions, this is fine to use.\n return predictions.pop()\n else:\n # Multiple predictions, so can't process this.\n raise ValueError(\n \"Track has MultipleHypothesis updates with multiple predictions.\")\n else:\n return state.hypothesis.prediction\n else:\n raise TypeError(\"States must be GaussianStatePredictions or GaussianStateUpdates.\")\n\n def _transition_model(self, state):\n \"\"\" If it exists, return the transition model from the prediction associated with input\n state. If that doesn't exist then use the (static) transition model defined by the\n smoother.\n\n Parameters\n ----------\n state : :class:`~.GaussianStatePrediction` or :class:`~.GaussianStateUpdate`\n\n Returns\n -------\n : :class:`~.TransitionModel`\n The transition model to be associated with state\n \"\"\"\n # Is there a transition model linked to the prediction?\n if getattr(self._prediction(state), \"transition_model\", None) is not None:\n transition_model = self._prediction(state).transition_model\n else: # No? Return the class attribute\n transition_model = self.transition_model\n\n return transition_model\n\n def _transition_matrix(self, state, **kwargs):\n \"\"\" Return the transition matrix\n\n Parameters\n ----------\n state : :class:`~.State`\n The input state (to check for a linked prediction)\n **kwargs\n These are passed to the :meth:`matrix()` function\n\n Returns\n -------\n : :class:`numpy.ndarray`\n The transition matrix\n \"\"\"\n return self._transition_model(state).matrix(**kwargs)\n\n def _smooth_gain(self, state, prediction, **kwargs):\n \"\"\"Calculate the smoothing gain\n\n Parameters\n ----------\n state : :class:`~.State`\n The input state\n prediction : :class:`~.GaussianStatePrediction`\n The prediction (from the subsequent state)\n\n Returns\n -------\n : Matrix\n The smoothing gain\n\n \"\"\"\n return state.covar @ self._transition_matrix(state, **kwargs).T @ np.linalg.inv(\n prediction.covar)\n\n def smooth(self, track):\n \"\"\"\n Perform the backward recursion to smooth the track.\n\n Parameters\n ----------\n track : :class:`~.Track`\n The input track.\n\n Returns\n -------\n : :class:`~.Track`\n Smoothed track\n\n \"\"\"\n subsq_state = track[-1]\n smoothed_states = [subsq_state]\n for state in reversed(track[:-1]):\n\n # Delta t\n time_interval = subsq_state.timestamp - state.timestamp\n\n # Retrieve the prediction from the subsequent (k+1th) timestep accessed previously\n prediction = self._prediction(subsq_state)\n # The smoothing gain, mean and covariance\n ksmooth_gain = self._smooth_gain(state, prediction, time_interval=time_interval)\n smooth_mean = state.state_vector + ksmooth_gain @ (subsq_state.state_vector -\n prediction.state_vector)\n smooth_covar = state.covar + \\\n ksmooth_gain @ (subsq_state.covar - prediction.covar) @ ksmooth_gain.T\n\n # Create a new type called SmoothedState?\n if isinstance(state, Update):\n subsq_state = Update.from_state(state, smooth_mean, smooth_covar,\n timestamp=state.timestamp,\n hypothesis=state.hypothesis)\n elif isinstance(state, Prediction):\n subsq_state = Prediction.from_state(state, smooth_mean, smooth_covar,\n timestamp=state.timestamp)\n\n smoothed_states.insert(0, subsq_state)\n\n # Deep copy existing track, but avoid copying original states, as this would be super\n # expensive. This works by informing deepcopy that the smoothed states are the\n # replacement object for the original track states.\n smoothed_track = copy.deepcopy(track, {id(track.states): smoothed_states})\n return smoothed_track\n\n\nclass ExtendedKalmanSmoother(KalmanSmoother):\n r\"\"\" The extended version of the Kalman smoother. The equations are modified slightly,\n analogously to the extended Kalman filter,\n\n .. math::\n\n \\mathbf{x}_{k|k-1} &= f_{k} (\\mathbf{x}_{k-1})\n\n F_k &\\approx J_f (\\mathbf{x}_{k-1})\n\n where :math:`J_f (\\mathbf{x}_{k-1})` is the Jacobian matrix evaluated at\n :math:`\\mathbf{x}_{k-1}`. The rest of the calculation proceeds as with the Kalman smoother.\n\n In fact the first equation isn't calculated -- it's presumed to have been undertaken by a\n filter when building the track; similarly for the predicted covariance. In practice, the only\n difference between this and the Kalman smoother is in the use of the linearised transition\n matrix to calculate the smoothing gain.\n\n \"\"\"\n transition_model: TransitionModel = Property(doc=\"The transition model to be used.\")\n\n def _transition_matrix(self, state, **kwargs):\n r\"\"\"Returns the transition matrix, a matrix if the model is linear, or\n approximated as Jacobian otherwise.\n\n Parameters\n ----------\n state : :class:`~.State`\n :math:`\\mathbf{x}_{k-1}`\n **kwargs : various, optional\n These are passed to :meth:`~.TransitionModel.matrix` or\n :meth:`~.TransitionModel.jacobian`\n\n Returns\n -------\n : :class:`numpy.ndarray`\n The transition matrix, :math:`F_k`, if linear (i.e.\n :meth:`TransitionModel.matrix` exists, or\n :meth:`~.TransitionModel.jacobian` if not)\n \"\"\"\n if isinstance(self._transition_model(state), LinearModel):\n return self._transition_model(state).matrix(**kwargs)\n else:\n return self._transition_model(state).jacobian(state, **kwargs)\n\n\nclass UnscentedKalmanSmoother(KalmanSmoother):\n r\"\"\"The unscented version of the Kalman filter. As with the parent version of the Kalman\n smoother, the mean and covariance of the prediction are retrieved from the track. The\n unscented transform is used to calculate the smoothing gain.\n\n \"\"\"\n transition_model: TransitionModel = Property(doc=\"The transition model to be used.\")\n\n alpha: float = Property(\n default=0.5,\n doc=\"Primary sigma point spread scaling parameter. Default is 0.5.\")\n beta: float = Property(\n default=2,\n doc=\"Used to incorporate prior knowledge of the distribution. If the \"\n \"true distribution is Gaussian, the value of 2 is optimal. \"\n \"Default is 2\")\n kappa: float = Property(\n default=0,\n doc=\"Secondary spread scaling parameter. Default is calculated as \"\n \"3-Ns\")\n\n def _smooth_gain(self, state, prediction, time_interval, **kwargs):\n \"\"\"Calculate the smoothing gain\n\n Parameters\n ----------\n state : :class:`~.State`\n The input state\n prediction : :class:`~.GaussianStatePrediction`\n The prediction from the subsequent timestep\n\n Returns\n -------\n : Matrix\n The smoothing gain\n\n \"\"\"\n # This ensures that the time interval is correctly applied.\n transition_function = partial(\n self._transition_model(state).function,\n time_interval=time_interval)\n\n # Get the sigma points from the mean and covariance.\n sigma_point_states, mean_weights, covar_weights = gauss2sigma(\n state, self.alpha, self.beta, self.kappa)\n\n # Use the unscented transform to return the cross-covariance\n _, _, cross_covar, _, _, _ = unscented_transform(\n sigma_point_states, mean_weights, covar_weights,\n transition_function)\n\n return cross_covar @ np.linalg.inv(prediction.covar)\n"
] | [
[
"numpy.linalg.inv"
]
] |
neherlab/HIVEVO_recombination | [
"3160d4396069c1a403a0a122d30e6c2f0522df5f"
] | [
"scripts/activity.py"
] | [
"from trajectory import Trajectory, create_trajectory_list, filter, create_all_patient_trajectories\nfrom hivevo.patients import Patient\nimport filenames\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef get_activity(patient, region, normalize=False, remove_one_point_traj=False, min_freq=0.2):\n time_bins = np.linspace(0, 2000, 30)\n aft = patient.get_allele_frequency_trajectories(region)\n trajectories = create_trajectory_list(patient, region, aft)\n filtered_traj = [traj for traj in trajectories if np.sum(traj.frequencies > min_freq, dtype=bool)]\n if remove_one_point_traj:\n filtered_traj = [traj for traj in filtered_traj if traj.t[-1] > 0] # Remove 1 point only trajectories\n\n filtered_fixed = [traj for traj in filtered_traj if traj.fixation == \"fixed\"]\n filtered_lost = [traj for traj in filtered_traj if traj.fixation == \"lost\"]\n filtered_active = [traj for traj in filtered_traj if traj.fixation == \"active\"]\n fixed, lost, active = [], [], []\n\n for ii in range(len(time_bins)):\n nb_fixed = len([traj for traj in filtered_fixed if traj.t[-1] < time_bins[ii]])\n nb_lost = len([traj for traj in filtered_lost if traj.t[-1] < time_bins[ii]])\n nb_active = len([traj for traj in filtered_traj if traj.t[-1] >= time_bins[ii]])\n # not adding len([traj for traj in filtered_active if traj.t[-1] < time_bins[ii]]) because we don't know how long they stay active as they are from last timepoint\n\n fixed = fixed + [nb_fixed]\n lost = lost + [nb_lost]\n active = active + [nb_active]\n\n sum = np.array(fixed) + np.array(lost) + np.array(active)\n\n if normalize:\n fixed = np.array(fixed) / sum\n lost = np.array(lost) / sum\n active = np.array(active) / sum\n sum = np.ones_like(fixed)\n return time_bins, fixed, lost, active, sum\n\n\ndef plot_activity(patient, region, time_bins, fixed, lost, active, sum, fontsize=16):\n plt.figure()\n plt.title(f\"Activity patient {patient.name} region {region}\", fontsize=fontsize)\n plt.plot(time_bins, fixed, label=\"fixed\")\n plt.plot(time_bins, lost, label=\"lost\")\n plt.plot(time_bins, active, label=\"active\")\n if sum[0] != 1:\n plt.plot(time_bins, sum, label=\"sum\")\n plt.legend(fontsize=fontsize)\n plt.xlabel(\"Time [days]\", fontsize=fontsize)\n plt.ylabel(\"# Trajectories\", fontsize=fontsize)\n plt.show()\n\n\ndef average_activity(patient_names, region, normalize=True, remove_one_point_traj=False, min_freq=0.2):\n for patient_name in patient_names:\n patient = Patient.load(patient_name)\n\n time_bins, fixed, lost, active, sum = get_activity(\n patient, region, False, remove_one_point_traj, min_freq)\n if patient_name == patient_names[0]:\n tot_fixed = np.array(fixed)\n tot_lost = np.array(lost)\n tot_active = np.array(active)\n tot_sum = np.array(sum)\n else:\n tot_fixed += fixed\n tot_lost += lost\n tot_active += active\n tot_sum += sum\n\n if normalize:\n tot_fixed = np.array(tot_fixed) / tot_sum\n tot_lost = np.array(tot_lost) / tot_sum\n tot_active = np.array(tot_active) / tot_sum\n tot_sum = np.ones_like(tot_fixed)\n\n return time_bins, tot_fixed, tot_lost, tot_active, tot_sum\n\n\ndef plot_average_activity(region, time_bins, fixed, lost, active, sum, fontsize=16):\n plt.figure(figsize=(10, 8))\n plt.title(f\"Average activity region {region}\", fontsize=fontsize)\n plt.plot(time_bins, fixed, label=\"fixed\")\n plt.plot(time_bins, lost, label=\"lost\")\n plt.plot(time_bins, active, label=\"active\")\n if sum[0] != 1:\n plt.plot(time_bins, sum, label=\"sum\")\n plt.legend(fontsize=fontsize)\n plt.xlabel(\"Time [days]\", fontsize=fontsize)\n plt.ylabel(\"# Trajectories\", fontsize=fontsize)\n plt.grid()\n plt.show()\n\n\ndef get_average_activity(trajectories, normalize=False, as_dict=True):\n \"\"\"\n Return the number of trajectories fixed; lost and active in time.\n \"\"\"\n time_bins = np.linspace(0, 2700, 40)\n filtered_fixed = [traj for traj in trajectories if traj.fixation == \"fixed\"]\n filtered_lost = [traj for traj in trajectories if traj.fixation == \"lost\"]\n filtered_active = [traj for traj in trajectories if traj.fixation == \"active\"]\n fixed, lost, active = [], [], []\n\n for ii in range(len(time_bins)):\n nb_fixed = len([traj for traj in filtered_fixed if traj.t[-1] < time_bins[ii]])\n nb_lost = len([traj for traj in filtered_lost if traj.t[-1] < time_bins[ii]])\n nb_active = len([traj for traj in trajectories if traj.t[-1] >= time_bins[ii]])\n # not adding len([traj for traj in filtered_active if traj.t[-1] < time_bins[ii]]) because we don't know how long they stay active as they are from last timepoint\n\n fixed = fixed + [nb_fixed]\n lost = lost + [nb_lost]\n active = active + [nb_active]\n\n sum = np.array(fixed) + np.array(lost) + np.array(active)\n\n if normalize:\n fixed = np.array(fixed) / sum\n lost = np.array(lost) / sum\n active = np.array(active) / sum\n sum = np.ones_like(fixed)\n\n if as_dict == True:\n return {\"time_bins\":time_bins, \"fixed\":fixed, \"lost\": lost, \"active\":active, \"sum\":sum}\n else:\n return time_bins, fixed, lost, active, sum\n\n\nif __name__ == \"__main__\":\n patient_names = [\"p1\", \"p2\", \"p3\", \"p4\", \"p5\", \"p6\", \"p8\", \"p9\", \"p11\"]\n region = \"env\"\n normalize = True\n remove_one_point_traj = True\n fontsize = 16\n\n trajectories = create_all_patient_trajectories(region)\n traj_syn = [traj for traj in trajectories if traj.synonymous == True]\n traj_non_syn = [traj for traj in trajectories if traj.synonymous == False]\n bins, syn_fixed, syn_lost, syn_active, syn_sum = get_average_activity(\n traj_syn, normalize, remove_one_point_traj)\n _, non_syn_fixed, non_syn_lost, non_syn_active, non_syn_sum = get_average_activity(\n traj_non_syn, normalize, remove_one_point_traj)\n\n plt.figure(figsize=(10, 8))\n plt.title(f\"Average activity region {region}\", fontsize=fontsize)\n plt.plot(bins, syn_fixed, label=\"syn_fixed\")\n plt.plot(bins, syn_lost, label=\"syn_lost\")\n plt.plot(bins, syn_active, label=\"syn_active\")\n plt.plot(bins, non_syn_fixed, label=\"non_syn_fixed\")\n plt.plot(bins, non_syn_lost, label=\"non_syn_lost\")\n plt.plot(bins, non_syn_active, label=\"non_syn_active\")\n plt.legend(fontsize=fontsize)\n plt.xlabel(\"Time [days]\", fontsize=fontsize)\n plt.ylabel(\"# Trajectories\", fontsize=fontsize)\n plt.grid()\n plt.show()\n"
] | [
[
"numpy.sum",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.grid",
"numpy.ones_like",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"numpy.array",
"matplotlib.pyplot.plot",
"numpy.linspace",
"matplotlib.pyplot.xlabel"
]
] |
amsks/SMARTS | [
"341ab5974bb77c90953536349e478d9b79994a64",
"341ab5974bb77c90953536349e478d9b79994a64"
] | [
"smarts/core/utils/math.py",
"scenarios/straight/agent_prefabs.py"
] | [
"# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.\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\n# all 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\n# THE SOFTWARE.\nimport math\nimport numpy as np\n\n\ndef batches(list_, n):\n \"\"\"Split an indexable container into `n` batches.\n\n Args:\n list_:\n The iterable to split into parts\n n:\n The number of batches\n \"\"\"\n for i in range(0, len(list_), n):\n yield list_[i : i + n]\n\n\ndef yaw_from_quaternion(quaternion) -> float:\n \"\"\"Converts a quaternion to the yaw value.\n\n Args:\n np.narray: np.array([x, y, z, w])\n\n Returns:\n A float angle in radians.\n \"\"\"\n assert len(quaternion) == 4, f\"len({quaternion}) != 4\"\n siny_cosp = 2 * (quaternion[0] * quaternion[1] + quaternion[3] * quaternion[2])\n cosy_cosp = (\n quaternion[3] ** 2\n + quaternion[0] ** 2\n - quaternion[1] ** 2\n - quaternion[2] ** 2\n )\n yaw = np.arctan2(siny_cosp, cosy_cosp)\n return yaw\n\n\ndef fast_quaternion_from_angle(angle: float) -> np.ndarray:\n \"\"\"Converts a float to a quaternion.\n\n Args:\n angle: An angle in radians.\n\n Returns:\n np.ndarray: np.array([x, y, z, w])\n \"\"\"\n\n half_angle = angle * 0.5\n return np.array([0, 0, math.sin(half_angle), math.cos(half_angle)])\n\n\ndef clip(val, min_val, max_val):\n assert (\n min_val <= max_val\n ), f\"min_val({min_val}) must be less than max_val({max_val})\"\n return min_val if val < min_val else max_val if val > max_val else val\n\n\ndef squared_dist(a, b) -> float:\n \"\"\"Computes the squared distance between a and b.\n\n Args:\n a, b: same dimension numpy.array([..])\n Returns:\n float: dist**2\n \"\"\"\n delta = b - a\n return np.dot(delta, delta)\n\n\ndef signed_dist_to_line(point, line_point, line_dir_vec) -> float:\n \"\"\"Computes the signed distance to a directed line\n\n The signed of the distance is:\n - negative if point is on the right of the line\n - positive if point is on the left of the line\n\n >>> import numpy as np\n >>> signed_dist_to_line(np.array([2, 0]), np.array([0, 0]), np.array([0, 1.]))\n -2.0\n >>> signed_dist_to_line(np.array([-1.5, 0]), np.array([0, 0]), np.array([0, 1.]))\n 1.5\n \"\"\"\n p = vec_2d(point)\n p1 = line_point\n p2 = line_point + line_dir_vec\n\n u = abs(\n line_dir_vec[1] * p[0] - line_dir_vec[0] * p[1] + p2[0] * p1[1] - p2[1] * p1[0]\n )\n d = u / np.linalg.norm(line_dir_vec)\n\n line_normal = np.array([-line_dir_vec[1], line_dir_vec[0]])\n _sign = np.sign(np.dot(p - p1, line_normal))\n return d * _sign\n\n\ndef vec_2d(v) -> np.ndarray:\n \"\"\"Converts a higher order vector to a 2D vector.\"\"\"\n\n assert len(v) >= 2\n return np.array(v[:2])\n\n\ndef sign(x) -> int:\n \"\"\"Finds the sign of a numeric type.\n\n Args:\n x: A signed numeric type\n Returns:\n The sign [-1|1] of the input number\n \"\"\"\n\n return 1 - (x < 0) * 2\n\n\ndef lerp(a, b, p):\n \"\"\"Linear interpolation between a and b with p\n\n .. math:: a * (1.0 - p) + b * p\n\n Args:\n a, b: interpolated values\n p: [0..1] float describing the weight of a to b\n \"\"\"\n\n assert 0 <= p and p <= 1\n\n return a * (1.0 - p) + b * p\n\n\ndef low_pass_filter(\n input_value,\n previous_filter_state,\n filter_constant,\n time_step,\n lower_bound=-1,\n raw_value=0,\n):\n previous_filter_state += (\n time_step * filter_constant * (input_value - previous_filter_state)\n )\n previous_filter_state = np.clip(previous_filter_state + raw_value, lower_bound, 1)\n return previous_filter_state\n\n\ndef radians_to_vec(radians) -> np.ndarray:\n # +y = 0 rad.\n angle = (radians + math.pi * 0.5) % (2 * math.pi)\n return np.array([math.cos(angle), math.sin(angle)])\n\n\ndef vec_to_radians(v) -> float:\n # See: https://stackoverflow.com/a/15130471\n assert len(v) == 2, f\"Vector must be 2D: {repr(v)}\"\n\n x, y = v\n r = math.atan2(abs(y), abs(x))\n\n quad = 0\n if x < 0:\n if y < 0:\n quad = 3\n else:\n quad = 2\n else:\n if y < 0:\n quad = 4\n\n # Adjust angle based on quadrant\n if 2 == quad:\n r = math.pi - r\n elif 3 == quad:\n r = math.pi + r\n elif 4 == quad:\n r = 2 * math.pi - r\n\n # +y = 0 rad.\n return (r - (math.pi) * 0.5) % (2 * math.pi)\n\n\ndef rotate_around_point(point, radians, origin=(0, 0)) -> np.ndarray:\n \"\"\"Rotate a point around a given origin.\"\"\"\n x, y = point\n ox, oy = origin\n\n qx = ox + math.cos(radians) * (x - ox) + math.sin(radians) * (y - oy)\n qy = oy + -math.sin(radians) * (x - ox) + math.cos(radians) * (y - oy)\n\n return np.array([qx, qy])\n\n\ndef min_angles_difference_signed(first, second) -> float:\n return ((first - second) + math.pi) % (2 * math.pi) - math.pi\n\n\ndef position_to_ego_frame(position, ego_position, ego_heading):\n \"\"\"\n Get the position in ego vehicle frame given the pose (of either a vehicle or some point) in global frame.\n Egocentric frame: The ego position becomes origin, and ego heading direction is positive x-axis.\n Args:\n position: [x,y,z]\n ego_position: Ego vehicle [x,y,z]\n ego_heading: Ego vehicle heading in radians\n\n Returns:\n new_pose: The pose [x,y,z] in egocentric view\n \"\"\"\n transform_matrix = np.eye(3)\n ego_rel_position = np.asarray(position) - np.asarray(ego_position)\n transform_matrix[0, 0] = np.cos(-ego_heading)\n transform_matrix[0, 1] = -np.sin(-ego_heading)\n transform_matrix[1, 0] = np.sin(-ego_heading)\n transform_matrix[1, 1] = np.cos(-ego_heading)\n\n new_position = np.matmul(transform_matrix, ego_rel_position.T).T\n return new_position.tolist()\n",
"import logging\n\nimport numpy as np\n\nfrom smarts.core.agent import Agent, AgentSpec\nfrom smarts.core.agent_interface import AgentInterface\nfrom smarts.core.controllers import ActionSpaceType\nfrom smarts.zoo.registry import register\n\n\nclass PoseBoidAgent(Agent):\n def __init__(self):\n self._log = logging.getLogger(self.__class__.__name__)\n self._log.info(f\"{self.__class__.__name__} was created\")\n\n def act(self, obs):\n returning = {\n vehicle_id: self._single_act(obs_) for vehicle_id, obs_ in obs.items()\n }\n return returning\n\n def _single_act(self, obs):\n wp = obs.waypoint_paths[0][:5][-1]\n dist_to_wp = np.linalg.norm(wp.pos - obs.ego_vehicle_state.position[:2])\n target_speed = 5 # m/s\n return np.array([*wp.pos, wp.heading, dist_to_wp / target_speed])\n\n\nclass TrajectoryBoidAgent(Agent):\n def __init__(self):\n self._log = logging.getLogger(self.__class__.__name__)\n self._log.info(f\"{self.__class__.__name__} was created\")\n\n def act(self, obs):\n returning = {\n vehicle_id: self._single_act(obs_) for vehicle_id, obs_ in obs.items()\n }\n return returning\n\n def _single_act(self, obs):\n lane_index = 0\n num_trajectory_points = min([10, len(obs.waypoint_paths[lane_index])])\n desired_speed = 50 / 3.6 # m/s\n trajectory = [\n [\n obs.waypoint_paths[lane_index][i].pos[0]\n for i in range(num_trajectory_points)\n ],\n [\n obs.waypoint_paths[lane_index][i].pos[1]\n for i in range(num_trajectory_points)\n ],\n [\n obs.waypoint_paths[lane_index][i].heading\n for i in range(num_trajectory_points)\n ],\n [desired_speed for i in range(num_trajectory_points)],\n ]\n return trajectory\n\n\nregister(\n locator=\"pose-boid-agent-v0\",\n entry_point=lambda **kwargs: AgentSpec(\n interface=AgentInterface(\n action=ActionSpaceType.MultiTargetPose, waypoints=True\n ),\n agent_builder=PoseBoidAgent,\n ),\n)\n\nregister(\n locator=\"trajectory-boid-agent-v0\",\n entry_point=lambda **kwargs: AgentSpec(\n interface=AgentInterface(action=ActionSpaceType.Trajectory, waypoints=True),\n agent_builder=TrajectoryBoidAgent,\n ),\n)\n"
] | [
[
"numpy.arctan2",
"numpy.eye",
"numpy.matmul",
"numpy.cos",
"numpy.asarray",
"numpy.clip",
"numpy.array",
"numpy.sin",
"numpy.dot",
"numpy.linalg.norm"
],
[
"numpy.array",
"numpy.linalg.norm"
]
] |
maximiliankc/photo-fun | [
"460f0b00d58c31ff2ed0283c6c4a07b9c481c9f0"
] | [
"dsp/dsp.py"
] | [
"import numpy as np\nimport matplotlib.pyplot as plt\n\n# W = J/sample\n\n## Filtering\n\ndef sinc_kernel(cutoff, halflength): # cutoff should be between 0 and 1, TODO window function, low-pass/highpass\n n = np.arange(-halflength, halflength + 1)\n # get the sinc function:\n out = np.sinc(cutoff*n)\n # return the normalised kernel\n return out/np.sum(out)\n\ndef fir_filt(signal, kernel, centre=0): # not dealing with edge effects at all, chopping the edges off\n out = np.convolve(signal, kernel)\n return out[centre:centre+signal.shape[0]]\n\ndef iir_filt(signal, a, b): # not dealing with edge effects at all, chopping the edges off\n # y[n] = ((m=0->∞)Σa_m*x[n-m] + (m=1->∞)Σb_m*y[n-m])/b_0\n # v[n] = (a * x)[n]\n # y[n] = (v[n] + <y_n,b>)/b_0\n v = fir_filt(signal, a)\n if b.size > 1:\n b1 = -b[1:]\n # print(b1)\n # print(b)\n # print(f\"b: {b}, b1: {b1}\")\n out = np.zeros(signal.shape)\n for n in range(signal.size):\n y_n = np.roll(out[-2::-1], n)[0:b1.size]\n # print(f\"out {n}: {out}\")\n # print(f\"out rd{n}: {out[-2::-1]}\")\n # print(f\"out randrd{n}: {np.roll(out[-2::-1], n+1)}\")\n # print(f\"b1: {b1}\")\n # print(f\"y_{n}: {y_n}\")\n # print(f\"<b1,y_n>: {np.vdot(b1,y_n)}\")\n out[n] = (np.vdot(b1,y_n) + v[n])/b[0]\n else:\n out = v/b\n return out\n\ndef resample(signal, N, M, kernelWidth=0): # resize by N/M\n # first, interpolate:\n bigger = np.zeros(N*signal.shape[0])\n for k in range(signal.size):\n bigger[N*k] = signal[k]\n # then filter:\n # first work out what the bandwidth of the filter should be:\n if N > M: # if the line is bigger than the original, restrict to the original bandwidth \n kernel = sinc_kernel(1/N, kernelWidth)\n else: # if it's smaller than the original, restrict to the new bandwidth\n kernel = M*sinc_kernel(1/M, kernelWidth)\n bigger = fir_filt(bigger, N*kernel, kernelWidth)\n # then decimate:\n smaller = np.zeros(bigger.size//M) # floor division\n for k in range(smaller.size):\n smaller[k] = bigger[M*k]\n return smaller\n\n# Synthesis\n\ndef impulse(N):\n x = np.zeros(N)\n x[0] = 1\n return x\n\ndef white_noise(std, length):\n return np.random.normal(0, std, length)\n\n# Analysis\n\ndef energy(x):\n # returns energy, average power\n E = np.vdot(x,x).real\n return [E, E/len(x)]\n\ndef psd(x, plot=False):\n X = np.fft.fft(x)/(len(x)**0.5)\n psd = (X*np.conj(X)).real\n w = np.linspace(0, 2.0, len(x))\n if plot:\n plt.ylabel('Magnitude (J/sample)')\n plt.xlabel('Frequency (π rad/sample)')\n plt.plot(w, psd)\n plt.show()\n return [psd, w]\n\ndef FT(x, plot=False, orthonormal=False):\n if orthonormal:\n norm = len(x)**0.5\n else:\n norm = 1\n X = np.fft.fft(x)/norm\n w = np.linspace(0, 2.0, len(x))\n if plot:\n plt.subplot(211)\n plt.ylabel('Magnitude')\n plt.plot(w, np.abs(X))\n plt.subplot(212)\n plt.xlabel('Frequency (π rad/sample)')\n plt.ylabel('Phase (rad)')\n plt.plot(w, np.angle(X))\n plt.show()\n return [X, w]\n\n# Test\ndef test_fir(): # need to figure out a metric\n N = 1024\n h = sinc_kernel(0.5,32)\n x = impulse(N)\n [X,_] = FT(x)\n y = fir_filt(x,h)\n [Y,w] = FT(y)\n hff = np.zeros(N)\n hff[0:h.size] = h\n [H,_] = FT(hff)\n\n plt.subplot(211)\n plt.ylabel('Magnitude')\n plt.plot(w, np.abs(Y/X))\n plt.plot(w, np.abs(H))\n plt.subplot(212)\n plt.xlabel('Frequency (π rad/sample)')\n plt.ylabel('Phase (rad)')\n plt.plot(w, np.angle(Y/X))\n plt.plot(w, np.angle(H))\n plt.show()\n\ndef test_iir():\n N = 1024\n a = np.array([1,])\n b = np.array([1,0,0.25])\n\n x = impulse(N)\n y = iir_filt(x, a, b)\n\n aff = np.zeros(N)\n bff = np.zeros(N)\n aff[0:a.size] = a\n bff[0:b.size] = b\n\n\n [A,w] = FT(aff)\n [B,_] = FT(bff)\n [X,_] = FT(x)\n [Y,_] = FT(y) \n\n plt.subplot(211)\n plt.ylabel('Magnitude')\n plt.plot(w, np.abs(Y/X))\n plt.plot(w, np.abs(A/B))\n plt.subplot(212)\n plt.xlabel('Frequency (π rad/sample)')\n plt.ylabel('Phase (rad)')\n plt.plot(w, np.angle(Y/X))\n plt.plot(w, np.angle(A/B))\n plt.show()\n\n\ndef main():\n test_fir()\n test_iir()\n\nif __name__ == \"__main__\":\n main()\n"
] | [
[
"numpy.sum",
"numpy.fft.fft",
"numpy.roll",
"numpy.zeros",
"numpy.conj",
"numpy.abs",
"numpy.arange",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"numpy.angle",
"numpy.sinc",
"numpy.random.normal",
"matplotlib.pyplot.plot",
"numpy.convolve",
"numpy.vdot",
"numpy.array",
"matplotlib.pyplot.xlabel"
]
] |
Phaeton-lang/baselines | [
"472c248047fbb55b5fa0e620758047b7f0a1d041"
] | [
"tensorflow-large-model-support/tflms-v2/test/manual/kerasload/ktk_resnet50_train_saveweights_h5.py"
] | [
"# Copyright 2018, 2019. IBM All Rights Reserved.\n# 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\n# This model uses the ResNet50 from keras_applications to demonstrate\n# how to enable TensorFlow Large Model Support (TFLMS) in a Keras model that\n# cannot fit in GPU memory when using larger resolution data. To simplify\n# the running of the model with different higher resolution images,\n# the code uses a random image generator to generate synthetic image data.\n#\n# This model provides a convenient way to test out the capabilities\n# of TFLMS. Command line parameters allow the user to change the size of\n# the input image data, enable or disable TFLMS, set TFLMS tunables,\n# and enable or disable CUDA profiling to ease collection of profile data.\n#\n# This model uses randomly generated synthetic image data. The random\n# generation is intentionally not using GPU operations to avoid impacting\n# the memory usage profile of the model. Since random generated images\n# are being used this code should not be used as an example on how to\n# correctly and efficiently pipeline data using datasets, etc.\n#\n# Invocation examples:\n# Run without LMS:\n# python Keras_ResNet50.py --image_size 2300\n# Run with LMS:\n# python Keras_ResNet50.py --image_size 3900 --lms\n\n\nimport argparse\nimport keras\nimport numpy as np\nfrom keras.callbacks import Callback\nfrom tensorflow_large_model_support import LMS\nimport ctypes\n_cudart = ctypes.CDLL('libcudart.so')\n\nclass CudaProfileCallback(Callback):\n def __init__(self, profile_epoch, profile_batch_start, profile_batch_end):\n self._epoch = profile_epoch - 1\n self._start = profile_batch_start\n self._end = profile_batch_end\n self.epoch_keeper = 0\n def on_epoch_begin(self, epoch, logs=None):\n self.epoch_keeper = epoch\n def on_batch_begin(self, batch, logs=None):\n if batch == self._start and self.epoch_keeper == self._epoch:\n print('Starting cuda profiler')\n _cudart.cudaProfilerStart()\n if batch == self._end and self.epoch_keeper == self._epoch:\n print('Stopping cuda profiler')\n _cudart.cudaProfilerStop()\n\ndef random_image_generator(batch_size, num_classes, input_shape):\n # This generator yields batches of randomly generated images and categories.\n # The random generation parts came from\n # https://github.com/tensorflow/tensorflow/blob/v1.12.0/tensorflow/python/keras/testing_utils.py#L29\n # These two random generations take a long time for large dimenstions and should\n # really be in the while loop below to have\n # better random images being generated for every yield. They were moved out of the while loop\n # to speed up the generator since the intent of this example is to show resolutions with\n # and without TFLMS versus a good data spread and loss / accuracy numbers.\n templates = 2 * num_classes * np.random.random((num_classes,) + input_shape)\n random_data = np.random.normal(loc=0, scale=1., size=input_shape)\n while True:\n y = np.random.randint(0, num_classes, size=(batch_size,))\n x = np.zeros((batch_size,) + input_shape, dtype=np.float32)\n for i in range(batch_size):\n x[i] = templates[y[i]] + random_data\n x_array = np.array(x)\n y_array = keras.utils.to_categorical(y, num_classes)\n yield(x_array, y_array)\n\ndef get_callbacks(args):\n callbacks = []\n\n if args.nvprof:\n callbacks.append(CudaProfileCallback(args.nvprof_epoch,\n args.nvprof_start,\n args.nvprof_stop))\n\n # Enable TFLMS\n if args.lms:\n # Specifying this starting name, from previous runs of LMS,\n # speeds up graph analysis time.\n lms = LMS(swapout_threshold=args.swapout_threshold,\n swapin_groupby=args.swapin_groupby,\n swapin_ahead=args.swapin_ahead)\n lms.batch_size = 1\n callbacks.append(lms)\n\n return callbacks\n\ndef run_model(args):\n\n image_dim = args.image_size\n input_shape = (image_dim, image_dim, 3)\n\n num_classes = 15\n batch_size = 1\n\n resnet50 = keras.applications.ResNet50(weights=None, include_top=True,\n input_shape=input_shape,\n classes=num_classes)\n resnet50.compile(optimizer='rmsprop', loss='categorical_crossentropy')\n #resnet50.load_weights('./checkpoints/my_checkpoint')\n #print('Loaded weights')\n random_generator = random_image_generator(batch_size, num_classes,\n input_shape)\n resnet50.fit_generator(random_generator, steps_per_epoch=args.steps,\n epochs=args.epochs, callbacks=get_callbacks(args))\n resnet50.save_weights('./h5weights.h5')\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--epochs\", type=int,\n default=1,\n help='Number of epochs to run. (Default 1)')\n parser.add_argument(\"--steps\", type=int,\n default=10,\n help='Number of steps per epoch. (Default 10)')\n parser.add_argument(\"--image_size\", type=int,\n default=500,\n help='Dimension of one side of the square image '\n 'to be generated. (Default 500)')\n # LMS parameters\n lms_group = parser.add_mutually_exclusive_group(required=False)\n lms_group.add_argument('--lms', dest='lms', action='store_true',\n help='Enable TFLMS')\n lms_group.add_argument('--no-lms', dest='lms', action='store_false',\n help='Disable TFLMS (Default)')\n parser.set_defaults(lms=False)\n parser.add_argument(\"--swapout_threshold\", type=int, default=-1,\n help='The TFLMS swapout_threshold parameter. See the '\n 'TFLMS documentation for more information. '\n 'Default `-1` (auto mode).')\n parser.add_argument(\"--swapin_groupby\", type=int, default=-1,\n help='The TFLMS swapin_groupby parameter. See the '\n 'TFLMS documentation for more information. '\n 'Default `-1` (auto mode).')\n parser.add_argument(\"--swapin_ahead\", type=int, default=-1,\n help='The TFLMS swapin_ahead parameter. See the '\n 'TFLMS documentation for more information. '\n 'Default `-1` (auto mode).')\n\n # nvprof parameters\n nvprof_group = parser.add_mutually_exclusive_group(required=False)\n nvprof_group.add_argument('--nvprof', dest='nvprof', action='store_true',\n help='Enable CUDA profilng for nvprof profiling.')\n nvprof_group.add_argument('--no-nvprof', dest='nvprof',\n action='store_false',\n help='Disable CUDA profilng for nvprof '\n 'profiling. (Default)')\n parser.set_defaults(nvprof=False)\n\n parser.add_argument(\"--nvprof_epoch\", type=int,\n default=1,\n help='The epoch in which to run CUDA profiling. '\n '(Default 1)')\n parser.add_argument(\"--nvprof_start\", type=int,\n default=4,\n help='The batch in which to start CUDA profiling. '\n '(Default 4)')\n parser.add_argument(\"--nvprof_stop\", type=int,\n default=9,\n help='The batch in which to stop CUDA profiling. '\n '(Default 9)')\n\n args = parser.parse_args()\n run_model(args)\n"
] | [
[
"numpy.zeros",
"numpy.random.random",
"numpy.random.normal",
"numpy.random.randint",
"numpy.array"
]
] |
Shiguang-Guo/fairseq | [
"c9d3df5679d0829cda8fc3c818b6cab52b78dc37"
] | [
"examples/MMPT/scripts/video_feature_extractor/shard_feature.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.\nimport numpy as np\nimport os\nimport pickle\n\nfrom mmpt.utils import ShardedTensor\n\n\nclass Shard(object):\n def __init__(\n self,\n vfeat_dir,\n tfeat_dir,\n target_dir,\n file_paths,\n shard_size=4096\n ):\n self.vfeat_dir = vfeat_dir\n self.tfeat_dir = tfeat_dir\n self.target_dir = target_dir\n self.video_ids = {}\n for split, file_path in zip([\"train\", \"val\"], file_paths):\n with open(file_path) as fr:\n self.video_ids[split] = [\n line.strip() for line in fr.readlines()]\n self.shard_size = shard_size\n\n def __call__(self, split=\"train\"):\n for split in [\"train\", \"val\"]:\n meta = {}\n for shard_idx, shard_offset in enumerate(\n range(0, len(self.video_ids[split]), self.shard_size)\n ):\n print(shard_idx)\n meta_shard = []\n video_shard = []\n for video_id in self.video_ids[split][shard_offset:shard_offset+self.shard_size]:\n meta_shard.append(video_id)\n npy_file = os.path.join(self.vfeat_dir, video_id + \".npy\")\n video_shard.append(np.load(npy_file))\n\n meta[shard_idx] = meta_shard\n video_shard = ShardedTensor.from_list(video_shard)\n target_path = os.path.join(\n self.target_dir, split + \"_\" + str(shard_idx))\n video_shard.save(target_path)\n\n target_path = os.path.join(self.target_dir, split + \"_meta\")\n with open(target_path + \".pkl\", \"wb\") as fw:\n pickle.dump(meta, fw, pickle.HIGHEST_PROTOCOL)\n\n\nif __name__ == \"__main__\":\n shard = Shard(\n \"data/feat/feat_how2_s3d\",\n \"data/how2/raw_caption_dedup.bert-base-uncased\",\n \"data/feat/feat_how2_s3d_shard_small\",\n [\"data/how2/how2_s3d_train.lst\", \"data/how2/how2_s3d_val.lst\"]\n )\n\n shard()\n"
] | [
[
"numpy.load"
]
] |
georgetown-analytics/Labor-Violations | [
"ce4a8fcd7b396f46a262636ef200b398b3d3e614"
] | [
"src/pipeline/text_pipeline_basic.py"
] | [
"# Built from the SKLearn basic text processing pipeine\n# https://scikit-learn.org/stable/auto_examples/model_selection/grid_search_text_feature_extraction.html\n\n\"\"\"\n==========================================================\nSample pipeline for text feature extraction and evaluation\n==========================================================\n\nThe dataset used in this example is the 20 newsgroups dataset which will be\nautomatically downloaded and then cached and reused for the document\nclassification example.\n\nYou can adjust the number of categories by giving their names to the dataset\nloader or setting them to None to get the 20 of them.\n\nHere is a sample output of a run on a quad-core machine::\n\n Loading 20 newsgroups dataset for categories:\n ['alt.atheism', 'talk.religion.misc']\n 1427 documents\n 2 categories\n\n Performing grid search...\n pipeline: ['vect', 'tfidf', 'clf']\n parameters:\n {'clf__alpha': (1.0000000000000001e-05, 9.9999999999999995e-07),\n 'clf__max_iter': (10, 50, 80),\n 'clf__penalty': ('l2', 'elasticnet'),\n 'tfidf__use_idf': (True, False),\n 'vect__max_n': (1, 2),\n 'vect__max_df': (0.5, 0.75, 1.0),\n 'vect__max_features': (None, 5000, 10000, 50000)}\n done in 1737.030s\n\n Best score: 0.940\n Best parameters set:\n clf__alpha: 9.9999999999999995e-07\n clf__max_iter: 50\n clf__penalty: 'elasticnet'\n tfidf__use_idf: True\n vect__max_n: 2\n vect__max_df: 0.75\n vect__max_features: 50000\n\n\"\"\"\n\n# Author: Olivier Grisel <[email protected]>\n# Peter Prettenhofer <[email protected]>\n# Mathieu Blondel <[email protected]>\n# License: BSD 3 clause\nfrom pprint import pprint\nfrom time import time\nimport logging\n\nfrom sklearn.datasets import fetch_20newsgroups\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.pipeline import Pipeline\n\nprint(__doc__)\n\n# Display progress logs on stdout\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s %(levelname)s %(message)s')\n\n\n# #############################################################################\n# Load some categories from the training set\ncategories = [\n 'alt.atheism',\n 'talk.religion.misc',\n]\n# Uncomment the following to do the analysis on all the categories\n#categories = None\n\nprint(\"Loading 20 newsgroups dataset for categories:\")\nprint(categories)\n\ndata = fetch_20newsgroups(subset='train', categories=categories)\nprint(\"%d documents\" % len(data.filenames))\nprint(\"%d categories\" % len(data.target_names))\nprint()\n\n# #############################################################################\n# Define a pipeline combining a text feature extractor with a simple\n# classifier\npipeline = Pipeline([\n ('vect', CountVectorizer()),\n ('tfidf', TfidfTransformer()),\n ('clf', SGDClassifier(tol=1e-3)),\n])\n\n# uncommenting more parameters will give better exploring power but will\n# increase processing time in a combinatorial way\nparameters = {\n 'vect__max_df': (0.5, 0.75, 1.0),\n # 'vect__max_features': (None, 5000, 10000, 50000),\n 'vect__ngram_range': ((1, 1), (1, 2)), # unigrams or bigrams\n # 'tfidf__use_idf': (True, False),\n # 'tfidf__norm': ('l1', 'l2'),\n 'clf__max_iter': (20,),\n 'clf__alpha': (0.00001, 0.000001),\n 'clf__penalty': ('l2', 'elasticnet'),\n # 'clf__max_iter': (10, 50, 80),\n}\n\nif __name__ == \"__main__\":\n # multiprocessing requires the fork to happen in a __main__ protected\n # block\n\n # find the best parameters for both the feature extraction and the\n # classifier\n grid_search = GridSearchCV(pipeline, parameters, cv=5,\n n_jobs=1, verbose=1)\n\n print(\"Performing grid search...\")\n print(\"pipeline:\", [name for name, _ in pipeline.steps])\n print(\"parameters:\")\n pprint(parameters)\n t0 = time()\n grid_search.fit(data.data, data.target)\n print(\"done in %0.3fs\" % (time() - t0))\n print()\n\n print(\"Best score: %0.3f\" % grid_search.best_score_)\n print(\"Best parameters set:\")\n best_parameters = grid_search.best_estimator_.get_params()\n for param_name in sorted(parameters.keys()):\n print(\"\\t%s: %r\" % (param_name, best_parameters[param_name]))\n\n # Add section to run model on test dataset\n # Display results\n"
] | [
[
"sklearn.feature_extraction.text.CountVectorizer",
"sklearn.linear_model.SGDClassifier",
"sklearn.feature_extraction.text.TfidfTransformer",
"sklearn.model_selection.GridSearchCV",
"sklearn.datasets.fetch_20newsgroups"
]
] |
laljarus/Programming_Self_Driving_Car | [
"b866f9cb176158badfa15d26b0a5c45e0aaf72bf"
] | [
"ros/src/tl_detector/tl_detector.py"
] | [
"#!/usr/bin/env python\nimport rospy\nfrom std_msgs.msg import Int32\nfrom geometry_msgs.msg import PoseStamped, Pose\nfrom styx_msgs.msg import TrafficLightArray, TrafficLight\nfrom styx_msgs.msg import Lane\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge\nfrom light_classification.tl_classifier import TLClassifier\nfrom scipy.spatial import KDTree\nimport numpy as np\nimport tf\nimport cv2\nimport yaml\nimport os\nimport csv\n\nSTATE_COUNT_THRESHOLD = 3\n\nclass TLDetector(object):\n def __init__(self):\n rospy.init_node('tl_detector')\n\n self.pose = None\n self.waypoints = None\n self.camera_image = None\n self.lights = []\n\n sub1 = rospy.Subscriber('/current_pose', PoseStamped, self.pose_cb)\n sub2 = rospy.Subscriber('/base_waypoints', Lane, self.waypoints_cb)\n\n '''\n /vehicle/traffic_lights provides you with the location of the traffic light in 3D map space and\n helps you acquire an accurate ground truth data source for the traffic light\n classifier by sending the current color state of all traffic lights in the\n simulator. When testing on the vehicle, the color state will not be available. You'll need to\n rely on the position of the light and the camera image to predict it.\n '''\n sub3 = rospy.Subscriber('/vehicle/traffic_lights', TrafficLightArray, self.traffic_cb)\n sub6 = rospy.Subscriber('/image_color', Image, self.image_cb)\n\n config_string = rospy.get_param(\"/traffic_light_config\")\n self.config = yaml.load(config_string)\n\n self.upcoming_red_light_pub = rospy.Publisher('/traffic_waypoint', Int32, queue_size=1)\n\n self.bridge = CvBridge()\n self.light_classifier = TLClassifier()\n self.listener = tf.TransformListener()\n\n self.state = TrafficLight.UNKNOWN\n self.last_state = TrafficLight.UNKNOWN\n self.last_wp = -1\n self.state_count = 0\n self.waypoints_2d = None\n self.waypoints_tree = None\n self.couter = 0\n self.LogEnabled = False\n #self.classifier = True\n\n base_path = os.path.dirname(os.path.abspath(__file__))\n self.labelfile = os.path.join(base_path, './ImageLog/ImagesLabel.csv')\n self.ImageData = []\n\n self.loop()\n\n def loop(self):\n rate = rospy.Rate(30)\n while not rospy.is_shutdown():\n rate.sleep()\n\n\n def pose_cb(self, msg):\n self.pose = msg\n\n def waypoints_cb(self, waypoints):\n self.waypoints = waypoints\n if not self.waypoints_2d:\n self.waypoints_2d = [[waypoint.pose.pose.position.x, waypoint.pose.pose.position.y] for waypoint in waypoints.waypoints]\n self.waypoints_tree = KDTree(self.waypoints_2d)\n\n def traffic_cb(self, msg):\n self.lights = msg.lights\n\n def image_cb(self, msg):\n \"\"\"Identifies red lights in the incoming camera image and publishes the index\n of the waypoint closest to the red light's stop line to /traffic_waypoint\n\n Args:\n msg (Image): image from car-mounted camera\n\n \"\"\"\n self.has_image = True\n self.camera_image = msg\n light_wp, state = self.process_traffic_lights()\n\n '''\n Publish upcoming red lights at camera frequency.\n Each predicted state has to occur `STATE_COUNT_THRESHOLD` number\n of times till we start using it. Otherwise the previous stable state is\n used.\n '''\n if self.state != state:\n self.state_count = 0\n self.state = state\n elif self.state_count >= STATE_COUNT_THRESHOLD:\n self.last_state = self.state\n light_wp = light_wp if (state == TrafficLight.RED) or (state == TrafficLight.YELLOW) else -1\n self.last_wp = light_wp\n self.upcoming_red_light_pub.publish(Int32(light_wp))\n else:\n self.upcoming_red_light_pub.publish(Int32(self.last_wp))\n self.state_count += 1\n\n def get_closest_waypoint(self, x,y):\n \"\"\"Identifies the closest path waypoint to the given position\n https://en.wikipedia.org/wiki/Closest_pair_of_points_problem\n Args:\n pose (Pose): position to match a waypoint to\n\n Returns:\n int: index of the closest waypoint in self.waypoints\n\n \"\"\"\n #TODO implement\n \n closest_idx = self.waypoints_tree.query([x,y],1)[1]\n\n closest_coord = self.waypoints_2d[closest_idx]\n prev_coord = self.waypoints_2d[closest_idx-1]\n\n cl_vector = np.array(closest_coord)\n prev_vector = np.array(prev_coord)\n pos_vector = np.array([x,y])\n\n dot_prod = np.dot(cl_vector - prev_vector, pos_vector - cl_vector)\n\n if dot_prod > 0:\n closest_idx = (closest_idx + 1) % len(self.waypoints_2d)\n\n return closest_idx\n\n def get_light_state(self, light):\n \"\"\"Determines the current color of the traffic light\n\n Args:\n light (TrafficLight): light to classify\n\n Returns:\n int: ID of traffic light color (specified in styx_msgs/TrafficLight)\n\n \"\"\"\n \n if(not self.has_image):\n self.prev_light_loc = None\n return False\n\n cv_image = self.bridge.imgmsg_to_cv2(self.camera_image, \"bgr8\")\n\n if self.LogEnabled:\n\n filename = \"./ImageLog/image_\"+str(self.couter)+\".png\"\n cv2.imwrite(filename,cv_image)\n self.couter += 1\n self.ImageData.append({'Path':filename,'Label':light.state})\n\n fieldnames = ['Path', 'Label']\n with open(self.labelfile, 'w') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n writer.writerows(self.ImageData)\n\n\n \n #Get classification\n \n #prediction = self.light_classifier.get_classification(cv_image)\n return self.light_classifier.get_classification(cv_image)\n #return light.state\n\n def process_traffic_lights(self):\n \"\"\"Finds closest visible traffic light, if one exists, and determines its\n location and color\n\n Returns:\n int: index of waypoint closes to the upcoming stop line for a traffic light (-1 if none exists)\n int: ID of traffic light color (specified in styx_msgs/TrafficLight)\n\n \"\"\"\n closest_light = None\n line_wp_idx = None \n\n # List of positions that correspond to the line to stop in front of for a given intersection\n stop_line_positions = self.config['stop_line_positions']\n if(self.pose):\n car_wp_idx = self.get_closest_waypoint(self.pose.pose.position.x,self.pose.pose.position.y)\n\n #TODO find the closest visible traffic light (if one exists)\n diff = len(self.waypoints.waypoints)\n for i,light in enumerate(self.lights):\n # get stop line waypoint index\n line = stop_line_positions[i]\n temp_wp_idx = self.get_closest_waypoint(line[0],line[1])\n \n # find stop line near closest light\n d = temp_wp_idx - car_wp_idx\n if d >=0 and d < diff:\n diff = d\n closest_light = light\n line_wp_idx = temp_wp_idx\n\n if closest_light:\n state = self.get_light_state(light)\n return line_wp_idx, state\n\n return -1, TrafficLight.UNKNOWN\n\nif __name__ == '__main__':\n try:\n TLDetector()\n except rospy.ROSInterruptException:\n rospy.logerr('Could not start traffic node.')\n"
] | [
[
"numpy.array",
"numpy.dot",
"scipy.spatial.KDTree"
]
] |
shibaji7/ISWAT_CV | [
"6239f021b597b66bca213cbc28ad7185f566c0f9"
] | [
"core/contours.py"
] | [
"\"\"\"contours.py: Module is used to implement edge detection tecqniues using CV2 and apply Kernel estimations on the regions\"\"\"\n\n__author__ = \"Chakraborty, S.\"\n__copyright__ = \"\"\n__credits__ = []\n__license__ = \"MIT\"\n__version__ = \"1.0.\"\n__maintainer__ = \"Chakraborty, S.\"\n__email__ = \"[email protected]\"\n__status__ = \"Research\"\n\nimport os\nimport matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\nimport datetime as dt\nimport pandas as pd\nimport json\nfrom scipy.stats import beta\nplt.style.context(\"seaborn\")\nfrom matplotlib import rcParams\nrcParams[\"font.family\"] = \"sans-serif\"\n\nimport matplotlib.pyplot as plt\nimport cv2\nimport os\n\nclass ProbabilisticContours(object):\n \"\"\" Probabilistic Contours detection by Open-CV \"\"\"\n \n def __init__(self, aia):\n np.random.seed(0)\n self.aia = aia\n self.filename = aia.fname\n self.folder = aia.folder\n self.file = aia.folder + aia.fname\n print(\" Proc file - \", self.file)\n self.extn = \".\" + aia.fname.split(\".\")[-1]\n self.binfile = self.folder + self.filename.replace(self.extn, \"_binmaps\" + self.extn)\n if os.path.exists(self.binfile): \n self.binmaps = cv2.imread(cv2.samples.findFile(self.binfile), cv2.IMREAD_GRAYSCALE)\n self.fcontours = (self.binmaps > 0).astype(int)\n if os.path.exists(self.aia.folder + self.aia.fname): self.aia.normalized()\n self.norm_data = self.aia.m_normalized.data * self.fcontours\n self.fcontours_nan = np.copy(self.fcontours).astype(float)\n self.fcontours_nan[self.fcontours_nan == 0] = np.nan\n else: raise Exception(\"File does not exists:\", self.binfile)\n return\n \n def probability_contours(self, v_range=(10, 300), v_step=10, pth=0.5, summary=True):\n _dict_ = {}\n for thd in range(v_range[0], v_range[1], v_step):\n _data = self.norm_data * self.fcontours_nan\n _intensity = (thd - _data).ravel()\n _intensity = _intensity[~np.isnan(_intensity)]\n _probs = 1./(1.+np.exp(_intensity))\n _hist, _bin_edges = np.histogram(_probs, bins=np.linspace(0,1,21), density=True)\n _idx = np.diff(_bin_edges)\n _f = pd.DataFrame(); _f[\"pr\"], _f[\"edgs\"], _f[\"idx\"] = _hist, _bin_edges[:-1], _idx\n _f = _f[_f.edgs >= pth]\n _mask = (self.norm_data <= thd).astype(int) * self.fcontours\n _dict_[thd] = (np.sum(_f.idx*_f.pr), _mask)\n if summary: self.generate_analysis_summary(\"norm\", _dict_)\n return _dict_\n \n def probability_contours_with_intensity_operation(self, v_range=(10, 300), v_step=10, pth=0.5, operations={\"name\":r\"Logarithm: $10\\times$ $log_{10}(x)$\",\"fn\":lambda x: 10*np.log10(x)}):\n _dict_ = {}\n \n return\n \n def generate_analysis_summary(self, kind=\"norm\", _dict_ = {}):\n \"\"\"\n Plot histograms for normalized intensity, thresholds and other parameters\n \"\"\"\n summary_folder = self.folder + \"summary/\"\n if not os.path.exists(summary_folder): os.mkdir(summary_folder)\n if kind==\"norm\": norm_data = np.copy(self.norm_data)\n for key in _dict_.keys():\n _p, _mask = _dict_[key]\n fig, ax = plt.subplots(dpi=180, figsize=(4,4), nrows=1, ncols=1)\n ax.imshow(_mask*255, extent=[-1024,1024,-1024,1024], cmap=\"gray\")\n ax.set_xticks([-1024,-512,0,512,1024])\n ax.set_yticks([-1024,-512,0,512,1024])\n ax.set_xticklabels([r\"-$2^{10}$\",r\"-$2^{9}$\",\"0\",r\"$2^{9}$\",r\"$2^{10}$\"])\n ax.set_yticklabels([r\"-$2^{10}$\",r\"-$2^{9}$\",\"0\",r\"$2^{9}$\",r\"$2^{10}$\"])\n ax.tick_params(axis=\"both\", which=\"major\", labelsize=8)\n ax.set_title(r\"$\\mathcal{F}(x_{\\tau},I_{th})$=%.3f, $x_{\\tau}$=0.5, $I_{th}$=%d\"%(_p,key), fontdict={\"size\":8})\n fig.savefig(summary_folder + self.filename.replace(self.extn, \"_binmaps_%04d\"%key + self.extn), bbox_inches=\"tight\")\n plt.close()\n os.system(\"zip -r summary.zip \" + summary_folder)\n return"
] | [
[
"numpy.sum",
"numpy.diff",
"pandas.DataFrame",
"numpy.random.seed",
"numpy.copy",
"matplotlib.pyplot.subplots",
"numpy.exp",
"numpy.log10",
"matplotlib.pyplot.close",
"numpy.isnan",
"matplotlib.use",
"numpy.linspace",
"matplotlib.pyplot.style.context"
]
] |
gogasca/tpu | [
"e8801a42e2e2217c464d6a7870e40f19f0ae936b"
] | [
"models/official/mask_rcnn/distributed_executer.py"
] | [
"# Copyright 2019 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\"\"\"Interface to run mask rcnn model in different distributed strategies.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport abc\nimport json\nimport os\nimport numpy as np\nimport tensorflow as tf\n\nfrom hyperparameters import params_dict\nimport evaluation\n\n\nclass DistributedExecuter(object):\n \"\"\"Interface to run Mask RCNN model in TPUs/GPUs.\n\n Arguments:\n flags: FLAGS object passed from the user.\n model_params: Model configuration needed to run distribution strategy.\n model_fn: Model function to be passed to Estimator.\n \"\"\"\n\n __metaclass__ = abc.ABCMeta\n\n def __init__(self, flags, model_params, model_fn):\n self._flags = flags\n self._model_params = model_params\n self._model_fn = model_fn\n\n @abc.abstractmethod\n def build_strategy_configuration(self):\n \"\"\"Builds run configuration for distributed train/eval.\n\n Returns:\n RunConfig with distribution strategy configurations\n to pass to the constructor of TPUEstimator/Estimator.\n \"\"\"\n\n NotImplementedError('Must be implmented in subclass')\n\n @abc.abstractmethod\n def build_model_parameters(self, unused_mode, unused_run_config):\n \"\"\"Builds model parameters.\n\n Returns:\n A dictionary to pass into `model_fn` of Estimator/TPUEstimator.\n \"\"\"\n\n NotImplementedError('Must be implmented in subclass')\n\n @abc.abstractmethod\n def build_mask_rcnn_estimator(self, params, run_config, mode):\n \"\"\"Creates TPUEstimator/Estimator instance.\n\n Arguments:\n params: A dictionary to pass to Estimator `model_fn`.\n run_config: RunConfig instance specifying distribution strategy\n configurations.\n mode: Mode -- one of 'train` or `eval`.\n\n Returns:\n TFEstimator or TPUEstimator instance.\n \"\"\"\n\n NotImplementedError('Must be implmented in subclass')\n\n def _save_config(self):\n \"\"\"Save parameters to config files if model_dir is defined.\"\"\"\n\n model_dir = self._flags.model_dir\n if model_dir is not None:\n if not tf.gfile.Exists(model_dir):\n tf.gfile.MakeDirs(model_dir)\n params_dict.save_params_dict_to_yaml(self._model_params,\n model_dir + '/params.yaml')\n\n def _write_summary(self, summary_writer, eval_results, predictions,\n current_step):\n if not self._model_params.visualize_images_summary:\n predictions = None\n evaluation.write_summary(\n eval_results, summary_writer, current_step, predictions=predictions)\n\n def train(self,\n train_input_fn,\n run_eval_after_train=False,\n eval_input_fn=None):\n \"\"\"Run distributed training on Mask RCNN model.\"\"\"\n\n self._save_config()\n run_config = self.build_strategy_configuration()\n params = self.build_model_parameters('train', run_config)\n tf.logging.info(params)\n train_estimator = self.build_mask_rcnn_estimator(params, run_config,\n 'train')\n if self._model_params.use_tpu:\n train_estimator.train(\n input_fn=train_input_fn, max_steps=self._model_params.total_steps)\n else:\n # As MirroredStrategy only supports `train_and_evaluate`, for training,\n # we pass dummy `eval_spec`.\n train_spec = tf.estimator.TrainSpec(\n input_fn=train_input_fn, max_steps=self._model_params.total_steps)\n eval_spec = tf.estimator.EvalSpec(input_fn=tf.data.Dataset)\n tf.estimator.train_and_evaluate(train_estimator, train_spec, eval_spec)\n\n eval_results = None\n if not run_eval_after_train:\n return eval_results\n\n if eval_input_fn is None:\n raise ValueError('Eval input_fn must be passed to conduct '\n 'evaluation after training.')\n\n eval_params = self.build_model_parameters('eval', run_config)\n eval_estimator = self.build_mask_rcnn_estimator(eval_params, run_config,\n 'eval')\n eval_results, predictions = evaluation.evaluate(\n eval_estimator, eval_input_fn, self._model_params.eval_samples,\n self._model_params.eval_batch_size, self._model_params.include_mask,\n self._model_params.val_json_file)\n\n output_dir = os.path.join(self._flags.model_dir, 'eval')\n tf.gfile.MakeDirs(output_dir)\n # Summary writer writes out eval metrics.\n summary_writer = tf.summary.FileWriter(output_dir)\n self._write_summary(summary_writer, eval_results, predictions,\n self._model_params.total_steps)\n summary_writer.close()\n\n return eval_results\n\n def eval(self, eval_input_fn):\n \"\"\"Run distributed eval on Mask RCNN model.\"\"\"\n\n output_dir = os.path.join(self._flags.model_dir, 'eval')\n tf.gfile.MakeDirs(output_dir)\n\n # Summary writer writes out eval metrics.\n summary_writer = tf.summary.FileWriter(output_dir)\n run_config = self.build_strategy_configuration()\n eval_params = self.build_model_parameters('eval', run_config)\n eval_estimator = self.build_mask_rcnn_estimator(eval_params, run_config,\n 'eval')\n\n def _terminate_eval():\n tf.logging.info('Terminating eval after %d seconds of '\n 'no checkpoints' % self._flags.eval_timeout)\n return True\n\n eval_results = None\n # Run evaluation when there's a new checkpoint\n for ckpt in tf.contrib.training.checkpoints_iterator(\n self._flags.model_dir,\n min_interval_secs=self._flags.min_eval_interval,\n timeout=self._flags.eval_timeout,\n timeout_fn=_terminate_eval):\n # Terminate eval job when final checkpoint is reached\n current_step = int(os.path.basename(ckpt).split('-')[1])\n\n tf.logging.info('Starting to evaluate.')\n try:\n eval_results, predictions = evaluation.evaluate(\n eval_estimator, eval_input_fn, self._model_params.eval_samples,\n self._model_params.eval_batch_size, self._model_params.include_mask,\n self._model_params.val_json_file)\n self._write_summary(summary_writer, eval_results, predictions,\n current_step)\n\n if current_step >= self._model_params.total_steps:\n tf.logging.info('Evaluation finished after training step %d' %\n current_step)\n break\n except tf.errors.NotFoundError:\n # Since the coordinator is on a different job than the TPU worker,\n # sometimes the TPU worker does not finish initializing until long after\n # the CPU job tells it to start evaluating. In this case, the checkpoint\n # file could have been deleted already.\n tf.logging.info('Checkpoint %s no longer exists, skipping checkpoint' %\n ckpt)\n summary_writer.close()\n return eval_results\n\n def train_and_eval(self, train_input_fn, eval_input_fn):\n \"\"\"Run distributed train and eval on Mask RCNN model.\"\"\"\n\n self._save_config()\n output_dir = os.path.join(self._flags.model_dir, 'eval')\n tf.gfile.MakeDirs(output_dir)\n summary_writer = tf.summary.FileWriter(output_dir)\n\n run_config = self.build_strategy_configuration()\n train_params = self.build_model_parameters('train', run_config)\n eval_params = self.build_model_parameters('eval', run_config)\n train_estimator = self.build_mask_rcnn_estimator(train_params, run_config,\n 'train')\n eval_estimator = self.build_mask_rcnn_estimator(eval_params, run_config,\n 'eval')\n\n num_cycles = int(self._model_params.total_steps /\n self._model_params.num_steps_per_eval)\n for cycle in range(num_cycles):\n tf.logging.info('Start training cycle %d.' % cycle)\n train_estimator.train(\n input_fn=train_input_fn, steps=self._model_params.num_steps_per_eval)\n\n tf.logging.info('Start evaluation cycle %d.' % cycle)\n eval_results, predictions = evaluation.evaluate(\n eval_estimator, eval_input_fn, self._model_params.eval_samples,\n self._model_params.eval_batch_size, self._model_params.include_mask,\n self._model_params.val_json_file)\n\n current_step = int(cycle * self._model_params.num_steps_per_eval)\n self._write_summary(summary_writer, eval_results, predictions,\n current_step)\n\n tf.logging.info('Starting training cycle %d.' % num_cycles)\n train_estimator.train(\n input_fn=train_input_fn, max_steps=self._model_params.total_steps)\n eval_results, predictions = evaluation.evaluate(\n eval_estimator, eval_input_fn, self._model_params.eval_samples,\n self._model_params.eval_batch_size, self._model_params.include_mask,\n self._model_params.val_json_file)\n self._write_summary(summary_writer, eval_results, predictions,\n self._model_params.total_steps)\n summary_writer.close()\n return eval_results\n\n\nclass TPUEstimatorExecuter(DistributedExecuter):\n \"\"\"Interface that runs Mask RCNN model using TPUEstimator.\"\"\"\n\n def build_strategy_configuration(self):\n \"\"\"Retrieves model configuration for running tpu estimator.\"\"\"\n\n if self._model_params.use_tpu:\n tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(\n self._flags.tpu,\n zone=self._flags.tpu_zone,\n project=self._flags.gcp_project)\n tpu_grpc_url = tpu_cluster_resolver.get_master()\n tf.Session.reset(tpu_grpc_url)\n else:\n tpu_cluster_resolver = None\n\n num_cores = self._model_params.num_cores\n input_partition_dims = self._flags.input_partition_dims\n\n # The following is for spatial partitioning. `features` has one tensor while\n # `labels` has 4 + (`max_level` - `min_level` + 1) * 2 tensors. The input\n # partition is performed on `features` and all partitionable tensors of\n # `labels`, see the partition logic below.\n # Note: In the below code, TPUEstimator uses both `shard` and `replica`\n # (with the same meaning).\n if input_partition_dims:\n labels_partition_dims = {\n 'gt_boxes': None,\n 'gt_classes': None,\n 'cropped_gt_masks': None,\n }\n # TODO(b/119617317): The Input Partition Logic. We partition only the\n # partition-able tensors. Spatial partition requires that the\n # to-be-partitioned tensors must have a dimension that is a multiple of\n # `partition_dims`. Depending on the `partition_dims` and the `image_size`\n # and the `max_level` in config, some high-level anchor labels (i.e.,\n # `cls_targets` and `box_targets`) cannot be partitioned. For example,\n # when `partition_dims` is [1, 4, 2, 1], image size is 1536, `max_level`\n # is 9, `cls_targets_8` has a shape of [batch_size, 6, 6, 9], which\n # cannot be partitioned (6 % 4 != 0). In this case, the level-8 and\n # level-9 target tensors are not partition-able, and the highest\n # partition-able level is 7.\n image_size = self._model_params.image_size\n for level in range(self._model_params.min_level,\n self._model_params.max_level + 1):\n\n def _can_partition(spatial_dim):\n partitionable_index = np.where(spatial_dim %\n np.array(input_partition_dims) == 0)\n return len(partitionable_index[0]) == len(input_partition_dims)\n\n assert len(image_size) == 2\n spatial_dim = [d // (2**level) for d in image_size]\n if _can_partition(spatial_dim[0]) and _can_partition(spatial_dim[1]):\n labels_partition_dims['box_targets_%d' % level] = input_partition_dims\n labels_partition_dims['score_targets_%d' %\n level] = input_partition_dims\n else:\n labels_partition_dims['box_targets_%d' % level] = None\n labels_partition_dims['score_targets_%d' % level] = None\n\n num_cores_per_replica = np.prod(input_partition_dims)\n transpose_input = self._model_params.transpose_input\n image_partition_dims = [input_partition_dims[i] for i in [1, 2, 3, 0]\n ] if transpose_input else input_partition_dims\n\n features_partition_dims = {\n 'images': image_partition_dims,\n 'source_ids': None,\n 'image_info': None,\n }\n input_partition_dims = [features_partition_dims, labels_partition_dims]\n num_shards = num_cores // num_cores_per_replica\n else:\n num_cores_per_replica = None\n input_partition_dims = None\n num_shards = num_cores\n\n tpu_config = tf.contrib.tpu.TPUConfig(\n self._model_params.iterations_per_loop,\n num_shards=num_shards,\n num_cores_per_replica=num_cores_per_replica,\n input_partition_dims=input_partition_dims,\n per_host_input_for_training=tf.contrib.tpu.InputPipelineConfig\n .PER_HOST_V2)\n run_config = tf.contrib.tpu.RunConfig(\n cluster=tpu_cluster_resolver,\n evaluation_master=self._flags.eval_master,\n model_dir=self._flags.model_dir,\n log_step_count_steps=self._model_params.iterations_per_loop,\n tpu_config=tpu_config,\n )\n return run_config\n\n def build_model_parameters(self, mode, run_config):\n assert mode in ('train', 'eval')\n params = dict(\n self._model_params.as_dict().items(),\n mode=self._flags.mode,\n model_dir=self._flags.model_dir,\n transpose_input=self._model_params.transpose_input,\n num_shards=run_config.tpu_config.num_shards,\n use_tpu=self._model_params.use_tpu,\n # Used by the host_call function.\n iterations_per_loop=self._model_params.iterations_per_loop)\n\n if mode == 'eval':\n params = dict(\n params,\n input_rand_hflip=False,\n is_training_bn=False,\n transpose_input=False)\n return params\n\n def build_mask_rcnn_estimator(self, params, run_config, unused_mode):\n estimator = tf.contrib.tpu.TPUEstimator(\n model_fn=self._model_fn,\n use_tpu=params['use_tpu'],\n train_batch_size=self._model_params.train_batch_size,\n eval_batch_size=self._model_params.eval_batch_size,\n predict_batch_size=self._model_params.eval_batch_size,\n config=run_config,\n params=params)\n return estimator\n\n\nclass MultiWorkerExecuter(DistributedExecuter):\n \"\"\"Interface that runs Mask RCNN model using MultiWorkerMirroredStrategy.\"\"\"\n\n @staticmethod\n def is_eval_task():\n return tf.contrib.cluster_resolver.TFConfigClusterResolver(\n ).task_type == 'evaluator'\n\n def build_strategy_configuration(self):\n \"\"\"Retrieves model configuration for MultiWorkerMirroredStrategy.\"\"\"\n\n worker_hosts = self._flags.worker_hosts\n\n if worker_hosts is not None:\n # Set TF_CONFIG environment variable\n worker_hosts = worker_hosts.split(',')\n task_index = self._flags.task_index\n os.environ['TF_CONFIG'] = json.dumps({\n 'cluster': {\n 'worker': worker_hosts\n },\n 'task': {\n 'type': 'worker',\n 'index': task_index\n }\n })\n\n multiworker_strategy = (\n tf.distribute.experimental.MultiWorkerMirroredStrategy())\n run_config = tf.estimator.RunConfig(\n train_distribute=multiworker_strategy, model_dir=self._flags.model_dir)\n return run_config\n\n def build_model_parameters(self, mode, unused_config):\n \"\"\"Builds model parameter to run in MultiWorkerMirroredStrategy.\"\"\"\n\n assert mode in ('train', 'eval')\n batch_size = (\n self._model_params.train_batch_size\n if mode == 'train' else self._model_params.eval_batch_size)\n params = dict(\n self._model_params.as_dict().items(),\n use_tpu=False,\n mode=mode,\n model_dir=self._flags.model_dir,\n # For MultiWorkerMirroredStrategy, we use CPU for evaluation and\n # CPU only supports channel-last data format. As so, we do not\n # transpose input by default to make data format consistent.\n transpose_input=False,\n batch_size=batch_size,\n precision='float32')\n return params\n\n def build_mask_rcnn_estimator(self, params, run_config, mode):\n \"\"\"Returns Mask Rcnn model running on MultiWorkerMirroredStrategy.\"\"\"\n assert mode in ('train', 'eval')\n if mode == 'train':\n return tf.estimator.Estimator(\n model_fn=self._model_fn,\n model_dir=self._flags.model_dir,\n config=run_config,\n params=params)\n\n # Evaluation on multi-worker mirrored strategy is done in CPU for now\n # as only `train_and_evaluate` is supported and eval pipeline for\n # Mask RCNN model is uses `predict` API.\n cpu_run_config = tf.estimator.RunConfig(model_dir=self._flags.model_dir)\n return tf.estimator.Estimator(\n model_fn=self._model_fn,\n model_dir=self._flags.model_dir,\n config=cpu_run_config,\n params=params)\n\n def train_and_eval(self, train_input_fn, eval_input_fn):\n if self.is_eval_task():\n assert eval_input_fn is not None\n self.eval(eval_input_fn)\n else:\n self.train(train_input_fn)\n"
] | [
[
"tensorflow.contrib.tpu.TPUEstimator",
"tensorflow.distribute.experimental.MultiWorkerMirroredStrategy",
"tensorflow.estimator.TrainSpec",
"tensorflow.contrib.cluster_resolver.TPUClusterResolver",
"tensorflow.summary.FileWriter",
"tensorflow.contrib.cluster_resolver.TFConfigClusterResolver",
"tensorflow.estimator.EvalSpec",
"tensorflow.contrib.tpu.TPUConfig",
"tensorflow.estimator.RunConfig",
"tensorflow.gfile.MakeDirs",
"tensorflow.gfile.Exists",
"tensorflow.contrib.tpu.RunConfig",
"numpy.prod",
"tensorflow.Session.reset",
"tensorflow.estimator.Estimator",
"tensorflow.logging.info",
"tensorflow.contrib.training.checkpoints_iterator",
"numpy.array",
"tensorflow.estimator.train_and_evaluate"
]
] |
exowanderer/BadPixelDetector | [
"1dd30eaec6f2a1c6edd40322cde395ac2cd06626"
] | [
"scripts/xgboost_simulated_bad_pixel_classifier.py"
] | [
"from itertools import product as iterproduct\n\nfrom pylab import *;ion()\nfrom sklearn.decomposition import PCA\n\nfrom sklearn.externals import joblib\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score, confusion_matrix\nfrom sklearn.preprocessing import StandardScaler\nfrom tqdm import tqdm\n\nfrom xgboost import XGBClassifier\n\nprint('[INFO]: Loading data')\ndata_dict = joblib.load('simulated_bad_pixels_df.joblib.save')\n\nprint('[INFO]: Selecting data')\nfeatures = data_dict['features']\nlabels = data_dict['labels']\n\nprint('[INFO]: Train Test Splitting')\nidx_train, idx_test = train_test_split(np.arange(labels.size), \n test_size=0.2,\n stratify=labels)\n\nprint('[INFO]: Transforming with PCA')\nstd_sclr = StandardScaler()\npca = PCA()\nfeatures_std_train = std_sclr.fit_transform(features[idx_train])\nfeatures_std_test = std_sclr.transform(features[idx_test])\n\nfeatures_pca_train = pca.fit_transform(features_std_train)\nfeatures_pca_test = pca.transform(features_std_test)\n\nprint('[INFO]: Establishing XGBoost Classifier')\nn_estimators = 10000\noob_score = True\nn_jobs = -1\nrfr = XGBClassifier(n_estimators=n_estimators, oob_score=oob_score, n_jobs=n_jobs)\n\nprint('[INFO]: Fitting Random Forest Classifier')\nrfr.fit(features_pca_train, labels[idx_train])\nprint('[INFO]: Finished Fitting Random Forest Classifier')\n\nprint('[INFO]: Predicting Random Forest Classifier')\npredict = rfr.predict(features_pca_test)\n\nprint('[INFO]: Computing Quality Metrics')\noob_score = rfr.oob_score_\naccuracy = accuracy_score(labels[idx_test], predict)\n\nnum_per_class = [(labels[idx_test] == label).sum() for label in set(labels)]\nconfusionMatrix = confusion_matrix(labels[idx_test], predict) / num_per_class\n\ndef plot_confusion_matrix(cm, classes,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n print(cm)\n\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in iterproduct(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n plt.tight_layout()\n\nclass_names = ['Clean', 'Hot Pixel', 'Cold Pixel', 'Sat Hot Pixel', 'Sat Cold Pixel', \n 'Cosmic Ray', 'Popcorn Pixel', 'Noisy']\nplot_confusion_matrix(confusionMatrix, classes=class_names, normalize=True,\n title='Normalized confusion matrix')\n\nfig = gcf()\nfig.savefig('RandomForest300_ConfusionMatrix.png')\n\ngotItRight = labels[idx_test] == predict\n\nclass_GIR = {classnow:np.where((labels[idx_test] == classnow)*gotItRight)[0][0] \\\n for classnow in set(labels) \\\n if np.any((labels[idx_test] == classnow)*gotItRight)}\n\nclass_nGIR = {classnow:np.where((labels[idx_test] == classnow)*(~gotItRight))[0][0] \\\n for classnow in set(labels) \\\n if np.any((labels[idx_test] == classnow)*(~gotItRight))}\n\n# Got It Right\nfor key, val in class_GIR.items(): \n # fig = figure()\n plt.plot(features[idx_test][val], label=class_names[predict[val]])\n \n legend(loc=4, fontsize=20, framealpha=0.9)\n \n xlim(0,110)\n ylabel('Electrons Read Off Detetor', fontsize=30)\n xlabel('Group Number [0,107]', fontsize=30)\n legend(loc=4, fontsize=15, framealpha=.9)\n title('Correctly Predicted', fontsize=30)\n \n ax = gcf().get_axes()[0]\n for tick in ax.xaxis.get_major_ticks():\n tick.label.set_fontsize(15)\n for tick in ax.yaxis.get_major_ticks():\n tick.label.set_fontsize(15)\n \n fig.savefig('Raw_data_correct_prediction.png')\n # fig.savefig('Raw_data_correct_prediction_{}.png'.format(class_names[predict[val]]))\n\n# not Got It Right\nfor key, val in class_nGIR.items(): \n fig = figure()\n plt.plot(features[idx_test][val], label=class_names[predict[val]])\n legend(loc=0, fontsize=20, framealpha=0.9)\n \n xlim(0,110)\n ylabel('Electrons Read Off Detetor', fontsize=30)\n xlabel('Group Number [0,107]', fontsize=30)\n legend(loc=4, fontsize=15, framealpha=.9)\n title('Incorrectly Predicted: {}'.format(class_names[predict[val]]), fontsize=30)\n \n ax = gcf().get_axes()[0]\n for tick in ax.xaxis.get_major_ticks():\n tick.label.set_fontsize(15)\n for tick in ax.yaxis.get_major_ticks():\n tick.label.set_fontsize(15)\n \n fig.savefig('Raw_data_wrong_prediction_{}.png'.format(class_names[predict[val]]))"
] | [
[
"sklearn.externals.joblib.load",
"sklearn.metrics.confusion_matrix",
"sklearn.metrics.accuracy_score",
"sklearn.preprocessing.StandardScaler",
"sklearn.decomposition.PCA"
]
] |
ptype/pandas | [
"672fb498bb4b4897c2caa2e17daad66d1ba60943"
] | [
"pandas/tests/indexes/test_base.py"
] | [
"from collections import defaultdict\nfrom datetime import (\n datetime,\n timedelta,\n)\nfrom io import StringIO\nimport math\nimport re\n\nimport numpy as np\nimport pytest\n\nfrom pandas.compat import (\n IS64,\n np_datetime64_compat,\n)\nfrom pandas.util._test_decorators import async_mark\n\nimport pandas as pd\nfrom pandas import (\n CategoricalIndex,\n DataFrame,\n DatetimeIndex,\n Float64Index,\n Int64Index,\n IntervalIndex,\n PeriodIndex,\n RangeIndex,\n Series,\n TimedeltaIndex,\n Timestamp,\n UInt64Index,\n date_range,\n isna,\n period_range,\n)\nimport pandas._testing as tm\nfrom pandas.core.indexes.api import (\n Index,\n MultiIndex,\n _get_combined_index,\n ensure_index,\n ensure_index_from_sequences,\n)\nfrom pandas.tests.indexes.common import Base\n\n\nclass TestIndex(Base):\n _index_cls = Index\n\n @pytest.fixture\n def simple_index(self) -> Index:\n return self._index_cls(list(\"abcde\"))\n\n def test_can_hold_identifiers(self, simple_index):\n index = simple_index\n key = index[0]\n assert index._can_hold_identifiers_and_holds_name(key) is True\n\n @pytest.mark.parametrize(\"index\", [\"datetime\"], indirect=True)\n def test_new_axis(self, index):\n with tm.assert_produces_warning(FutureWarning):\n # GH#30588 multi-dimensional indexing deprecated\n new_index = index[None, :]\n assert new_index.ndim == 2\n assert isinstance(new_index, np.ndarray)\n\n def test_constructor_regular(self, index):\n tm.assert_contains_all(index, index)\n\n @pytest.mark.parametrize(\"index\", [\"string\"], indirect=True)\n def test_constructor_casting(self, index):\n # casting\n arr = np.array(index)\n new_index = Index(arr)\n tm.assert_contains_all(arr, new_index)\n tm.assert_index_equal(index, new_index)\n\n @pytest.mark.parametrize(\"index\", [\"string\"], indirect=True)\n def test_constructor_copy(self, index):\n arr = np.array(index)\n new_index = Index(arr, copy=True, name=\"name\")\n assert isinstance(new_index, Index)\n assert new_index.name == \"name\"\n tm.assert_numpy_array_equal(arr, new_index.values)\n arr[0] = \"SOMEBIGLONGSTRING\"\n assert new_index[0] != \"SOMEBIGLONGSTRING\"\n\n # FIXME: dont leave commented-out\n # what to do here?\n # arr = np.array(5.)\n # pytest.raises(Exception, arr.view, Index)\n\n @pytest.mark.parametrize(\"cast_as_obj\", [True, False])\n @pytest.mark.parametrize(\n \"index\",\n [\n date_range(\n \"2015-01-01 10:00\",\n freq=\"D\",\n periods=3,\n tz=\"US/Eastern\",\n name=\"Green Eggs & Ham\",\n ), # DTI with tz\n date_range(\"2015-01-01 10:00\", freq=\"D\", periods=3), # DTI no tz\n pd.timedelta_range(\"1 days\", freq=\"D\", periods=3), # td\n period_range(\"2015-01-01\", freq=\"D\", periods=3), # period\n ],\n )\n def test_constructor_from_index_dtlike(self, cast_as_obj, index):\n if cast_as_obj:\n result = Index(index.astype(object))\n else:\n result = Index(index)\n\n tm.assert_index_equal(result, index)\n\n if isinstance(index, DatetimeIndex):\n assert result.tz == index.tz\n if cast_as_obj:\n # GH#23524 check that Index(dti, dtype=object) does not\n # incorrectly raise ValueError, and that nanoseconds are not\n # dropped\n index += pd.Timedelta(nanoseconds=50)\n result = Index(index, dtype=object)\n assert result.dtype == np.object_\n assert list(result) == list(index)\n\n @pytest.mark.parametrize(\n \"index,has_tz\",\n [\n (\n date_range(\"2015-01-01 10:00\", freq=\"D\", periods=3, tz=\"US/Eastern\"),\n True,\n ), # datetimetz\n (pd.timedelta_range(\"1 days\", freq=\"D\", periods=3), False), # td\n (period_range(\"2015-01-01\", freq=\"D\", periods=3), False), # period\n ],\n )\n def test_constructor_from_series_dtlike(self, index, has_tz):\n result = Index(Series(index))\n tm.assert_index_equal(result, index)\n\n if has_tz:\n assert result.tz == index.tz\n\n def test_constructor_from_series_freq(self):\n # GH 6273\n # create from a series, passing a freq\n dts = [\"1-1-1990\", \"2-1-1990\", \"3-1-1990\", \"4-1-1990\", \"5-1-1990\"]\n expected = DatetimeIndex(dts, freq=\"MS\")\n\n s = Series(pd.to_datetime(dts))\n result = DatetimeIndex(s, freq=\"MS\")\n\n tm.assert_index_equal(result, expected)\n\n def test_constructor_from_frame_series_freq(self):\n # GH 6273\n # create from a series, passing a freq\n dts = [\"1-1-1990\", \"2-1-1990\", \"3-1-1990\", \"4-1-1990\", \"5-1-1990\"]\n expected = DatetimeIndex(dts, freq=\"MS\")\n\n df = DataFrame(np.random.rand(5, 3))\n df[\"date\"] = dts\n result = DatetimeIndex(df[\"date\"], freq=\"MS\")\n\n assert df[\"date\"].dtype == object\n expected.name = \"date\"\n tm.assert_index_equal(result, expected)\n\n expected = Series(dts, name=\"date\")\n tm.assert_series_equal(df[\"date\"], expected)\n\n # GH 6274\n # infer freq of same\n freq = pd.infer_freq(df[\"date\"])\n assert freq == \"MS\"\n\n @pytest.mark.parametrize(\n \"array\",\n [\n np.arange(5),\n np.array([\"a\", \"b\", \"c\"]),\n date_range(\"2000-01-01\", periods=3).values,\n ],\n )\n def test_constructor_ndarray_like(self, array):\n # GH 5460#issuecomment-44474502\n # it should be possible to convert any object that satisfies the numpy\n # ndarray interface directly into an Index\n class ArrayLike:\n def __init__(self, array):\n self.array = array\n\n def __array__(self, dtype=None) -> np.ndarray:\n return self.array\n\n expected = Index(array)\n result = Index(ArrayLike(array))\n tm.assert_index_equal(result, expected)\n\n def test_constructor_int_dtype_nan(self):\n # see gh-15187\n data = [np.nan]\n expected = Float64Index(data)\n result = Index(data, dtype=\"float\")\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\"dtype\", [\"int64\", \"uint64\"])\n def test_constructor_int_dtype_nan_raises(self, dtype):\n # see gh-15187\n data = [np.nan]\n msg = \"cannot convert\"\n with pytest.raises(ValueError, match=msg):\n Index(data, dtype=dtype)\n\n def test_constructor_no_pandas_array(self):\n ser = Series([1, 2, 3])\n result = Index(ser.array)\n expected = Index([1, 2, 3])\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"klass,dtype,na_val\",\n [\n (Float64Index, np.float64, np.nan),\n (DatetimeIndex, \"datetime64[ns]\", pd.NaT),\n ],\n )\n def test_index_ctor_infer_nan_nat(self, klass, dtype, na_val):\n # GH 13467\n na_list = [na_val, na_val]\n expected = klass(na_list)\n assert expected.dtype == dtype\n\n result = Index(na_list)\n tm.assert_index_equal(result, expected)\n\n result = Index(np.array(na_list))\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"vals,dtype\",\n [\n ([1, 2, 3, 4, 5], \"int\"),\n ([1.1, np.nan, 2.2, 3.0], \"float\"),\n ([\"A\", \"B\", \"C\", np.nan], \"obj\"),\n ],\n )\n def test_constructor_simple_new(self, vals, dtype):\n index = Index(vals, name=dtype)\n result = index._simple_new(index.values, dtype)\n tm.assert_index_equal(result, index)\n\n @pytest.mark.parametrize(\n \"vals\",\n [\n [1, 2, 3],\n np.array([1, 2, 3]),\n np.array([1, 2, 3], dtype=int),\n # below should coerce\n [1.0, 2.0, 3.0],\n np.array([1.0, 2.0, 3.0], dtype=float),\n ],\n )\n def test_constructor_dtypes_to_int64(self, vals):\n index = Index(vals, dtype=int)\n assert isinstance(index, Int64Index)\n\n @pytest.mark.parametrize(\n \"vals\",\n [\n [1, 2, 3],\n [1.0, 2.0, 3.0],\n np.array([1.0, 2.0, 3.0]),\n np.array([1, 2, 3], dtype=int),\n np.array([1.0, 2.0, 3.0], dtype=float),\n ],\n )\n def test_constructor_dtypes_to_float64(self, vals):\n index = Index(vals, dtype=float)\n assert isinstance(index, Float64Index)\n\n @pytest.mark.parametrize(\n \"vals\",\n [\n [1, 2, 3],\n np.array([1, 2, 3], dtype=int),\n np.array(\n [np_datetime64_compat(\"2011-01-01\"), np_datetime64_compat(\"2011-01-02\")]\n ),\n [datetime(2011, 1, 1), datetime(2011, 1, 2)],\n ],\n )\n def test_constructor_dtypes_to_categorical(self, vals):\n index = Index(vals, dtype=\"category\")\n assert isinstance(index, CategoricalIndex)\n\n @pytest.mark.parametrize(\"cast_index\", [True, False])\n @pytest.mark.parametrize(\n \"vals\",\n [\n Index(\n np.array(\n [\n np_datetime64_compat(\"2011-01-01\"),\n np_datetime64_compat(\"2011-01-02\"),\n ]\n )\n ),\n Index([datetime(2011, 1, 1), datetime(2011, 1, 2)]),\n ],\n )\n def test_constructor_dtypes_to_datetime(self, cast_index, vals):\n if cast_index:\n index = Index(vals, dtype=object)\n assert isinstance(index, Index)\n assert index.dtype == object\n else:\n index = Index(vals)\n assert isinstance(index, DatetimeIndex)\n\n @pytest.mark.parametrize(\"cast_index\", [True, False])\n @pytest.mark.parametrize(\n \"vals\",\n [\n np.array([np.timedelta64(1, \"D\"), np.timedelta64(1, \"D\")]),\n [timedelta(1), timedelta(1)],\n ],\n )\n def test_constructor_dtypes_to_timedelta(self, cast_index, vals):\n if cast_index:\n index = Index(vals, dtype=object)\n assert isinstance(index, Index)\n assert index.dtype == object\n else:\n index = Index(vals)\n assert isinstance(index, TimedeltaIndex)\n\n @pytest.mark.filterwarnings(\"ignore:Passing keywords other:FutureWarning\")\n @pytest.mark.parametrize(\"attr\", [\"values\", \"asi8\"])\n @pytest.mark.parametrize(\"klass\", [Index, DatetimeIndex])\n def test_constructor_dtypes_datetime(self, tz_naive_fixture, attr, klass):\n # Test constructing with a datetimetz dtype\n # .values produces numpy datetimes, so these are considered naive\n # .asi8 produces integers, so these are considered epoch timestamps\n # ^the above will be true in a later version. Right now we `.view`\n # the i8 values as NS_DTYPE, effectively treating them as wall times.\n index = date_range(\"2011-01-01\", periods=5)\n arg = getattr(index, attr)\n index = index.tz_localize(tz_naive_fixture)\n dtype = index.dtype\n\n warn = None if tz_naive_fixture is None else FutureWarning\n # astype dt64 -> dt64tz deprecated\n\n if attr == \"asi8\":\n result = DatetimeIndex(arg).tz_localize(tz_naive_fixture)\n else:\n result = klass(arg, tz=tz_naive_fixture)\n tm.assert_index_equal(result, index)\n\n if attr == \"asi8\":\n with tm.assert_produces_warning(warn):\n result = DatetimeIndex(arg).astype(dtype)\n else:\n result = klass(arg, dtype=dtype)\n tm.assert_index_equal(result, index)\n\n if attr == \"asi8\":\n result = DatetimeIndex(list(arg)).tz_localize(tz_naive_fixture)\n else:\n result = klass(list(arg), tz=tz_naive_fixture)\n tm.assert_index_equal(result, index)\n\n if attr == \"asi8\":\n with tm.assert_produces_warning(warn):\n result = DatetimeIndex(list(arg)).astype(dtype)\n else:\n result = klass(list(arg), dtype=dtype)\n tm.assert_index_equal(result, index)\n\n @pytest.mark.parametrize(\"attr\", [\"values\", \"asi8\"])\n @pytest.mark.parametrize(\"klass\", [Index, TimedeltaIndex])\n def test_constructor_dtypes_timedelta(self, attr, klass):\n index = pd.timedelta_range(\"1 days\", periods=5)\n index = index._with_freq(None) # won't be preserved by constructors\n dtype = index.dtype\n\n values = getattr(index, attr)\n\n result = klass(values, dtype=dtype)\n tm.assert_index_equal(result, index)\n\n result = klass(list(values), dtype=dtype)\n tm.assert_index_equal(result, index)\n\n @pytest.mark.parametrize(\"value\", [[], iter([]), (_ for _ in [])])\n @pytest.mark.parametrize(\n \"klass\",\n [\n Index,\n Float64Index,\n Int64Index,\n UInt64Index,\n CategoricalIndex,\n DatetimeIndex,\n TimedeltaIndex,\n ],\n )\n def test_constructor_empty(self, value, klass):\n empty = klass(value)\n assert isinstance(empty, klass)\n assert not len(empty)\n\n @pytest.mark.parametrize(\n \"empty,klass\",\n [\n (PeriodIndex([], freq=\"B\"), PeriodIndex),\n (PeriodIndex(iter([]), freq=\"B\"), PeriodIndex),\n (PeriodIndex((_ for _ in []), freq=\"B\"), PeriodIndex),\n (RangeIndex(step=1), RangeIndex),\n (MultiIndex(levels=[[1, 2], [\"blue\", \"red\"]], codes=[[], []]), MultiIndex),\n ],\n )\n def test_constructor_empty_special(self, empty, klass):\n assert isinstance(empty, klass)\n assert not len(empty)\n\n def test_constructor_overflow_int64(self):\n # see gh-15832\n msg = (\n \"The elements provided in the data cannot \"\n \"all be casted to the dtype int64\"\n )\n with pytest.raises(OverflowError, match=msg):\n Index([np.iinfo(np.uint64).max - 1], dtype=\"int64\")\n\n @pytest.mark.parametrize(\n \"index\",\n [\n \"datetime\",\n \"float\",\n \"int\",\n \"period\",\n \"range\",\n \"repeats\",\n \"timedelta\",\n \"tuples\",\n \"uint\",\n ],\n indirect=True,\n )\n def test_view_with_args(self, index):\n index.view(\"i8\")\n\n @pytest.mark.parametrize(\n \"index\",\n [\n \"unicode\",\n \"string\",\n pytest.param(\"categorical\", marks=pytest.mark.xfail(reason=\"gh-25464\")),\n \"bool\",\n \"empty\",\n ],\n indirect=True,\n )\n def test_view_with_args_object_array_raises(self, index):\n msg = \"Cannot change data-type for object array\"\n with pytest.raises(TypeError, match=msg):\n index.view(\"i8\")\n\n @pytest.mark.parametrize(\"index\", [\"int\", \"range\"], indirect=True)\n def test_astype(self, index):\n casted = index.astype(\"i8\")\n\n # it works!\n casted.get_loc(5)\n\n # pass on name\n index.name = \"foobar\"\n casted = index.astype(\"i8\")\n assert casted.name == \"foobar\"\n\n def test_equals_object(self):\n # same\n assert Index([\"a\", \"b\", \"c\"]).equals(Index([\"a\", \"b\", \"c\"]))\n\n @pytest.mark.parametrize(\n \"comp\", [Index([\"a\", \"b\"]), Index([\"a\", \"b\", \"d\"]), [\"a\", \"b\", \"c\"]]\n )\n def test_not_equals_object(self, comp):\n assert not Index([\"a\", \"b\", \"c\"]).equals(comp)\n\n def test_insert_missing(self, nulls_fixture):\n # GH 22295\n # test there is no mangling of NA values\n expected = Index([\"a\", nulls_fixture, \"b\", \"c\"])\n result = Index(list(\"abc\")).insert(1, nulls_fixture)\n tm.assert_index_equal(result, expected)\n\n def test_delete_raises(self):\n index = Index([\"a\", \"b\", \"c\", \"d\"], name=\"index\")\n msg = \"index 5 is out of bounds for axis 0 with size 4\"\n with pytest.raises(IndexError, match=msg):\n index.delete(5)\n\n def test_identical(self):\n\n # index\n i1 = Index([\"a\", \"b\", \"c\"])\n i2 = Index([\"a\", \"b\", \"c\"])\n\n assert i1.identical(i2)\n\n i1 = i1.rename(\"foo\")\n assert i1.equals(i2)\n assert not i1.identical(i2)\n\n i2 = i2.rename(\"foo\")\n assert i1.identical(i2)\n\n i3 = Index([(\"a\", \"a\"), (\"a\", \"b\"), (\"b\", \"a\")])\n i4 = Index([(\"a\", \"a\"), (\"a\", \"b\"), (\"b\", \"a\")], tupleize_cols=False)\n assert not i3.identical(i4)\n\n def test_is_(self):\n ind = Index(range(10))\n assert ind.is_(ind)\n assert ind.is_(ind.view().view().view().view())\n assert not ind.is_(Index(range(10)))\n assert not ind.is_(ind.copy())\n assert not ind.is_(ind.copy(deep=False))\n assert not ind.is_(ind[:])\n assert not ind.is_(np.array(range(10)))\n\n # quasi-implementation dependent\n assert ind.is_(ind.view())\n ind2 = ind.view()\n ind2.name = \"bob\"\n assert ind.is_(ind2)\n assert ind2.is_(ind)\n # doesn't matter if Indices are *actually* views of underlying data,\n assert not ind.is_(Index(ind.values))\n arr = np.array(range(1, 11))\n ind1 = Index(arr, copy=False)\n ind2 = Index(arr, copy=False)\n assert not ind1.is_(ind2)\n\n @pytest.mark.parametrize(\"index\", [\"datetime\"], indirect=True)\n def test_asof(self, index):\n d = index[0]\n assert index.asof(d) == d\n assert isna(index.asof(d - timedelta(1)))\n\n d = index[-1]\n assert index.asof(d + timedelta(1)) == d\n\n d = index[0].to_pydatetime()\n assert isinstance(index.asof(d), Timestamp)\n\n def test_asof_numeric_vs_bool_raises(self):\n left = Index([1, 2, 3])\n right = Index([True, False])\n\n msg = \"'<' not supported between instances\"\n with pytest.raises(TypeError, match=msg):\n left.asof(right)\n\n with pytest.raises(TypeError, match=msg):\n right.asof(left)\n\n # TODO: this tests Series.asof\n def test_asof_nanosecond_index_access(self):\n s = Timestamp(\"20130101\").value\n r = DatetimeIndex([s + 50 + i for i in range(100)])\n ser = Series(np.random.randn(100), index=r)\n\n first_value = ser.asof(ser.index[0])\n\n # this does not yet work, as parsing strings is done via dateutil\n # assert first_value == x['2013-01-01 00:00:00.000000050+0000']\n\n expected_ts = np_datetime64_compat(\"2013-01-01 00:00:00.000000050+0000\", \"ns\")\n assert first_value == ser[Timestamp(expected_ts)]\n\n @pytest.mark.parametrize(\"index\", [\"string\"], indirect=True)\n def test_booleanindex(self, index):\n bool_index = np.ones(len(index), dtype=bool)\n bool_index[5:30:2] = False\n\n sub_index = index[bool_index]\n\n for i, val in enumerate(sub_index):\n assert sub_index.get_loc(val) == i\n\n sub_index = index[list(bool_index)]\n for i, val in enumerate(sub_index):\n assert sub_index.get_loc(val) == i\n\n def test_fancy(self, simple_index):\n index = simple_index\n sl = index[[1, 2, 3]]\n for i in sl:\n assert i == sl[sl.get_loc(i)]\n\n @pytest.mark.parametrize(\"index\", [\"string\", \"int\", \"float\"], indirect=True)\n @pytest.mark.parametrize(\"dtype\", [np.int_, np.bool_])\n def test_empty_fancy(self, index, dtype):\n empty_arr = np.array([], dtype=dtype)\n empty_index = type(index)([])\n\n assert index[[]].identical(empty_index)\n assert index[empty_arr].identical(empty_index)\n\n @pytest.mark.parametrize(\"index\", [\"string\", \"int\", \"float\"], indirect=True)\n def test_empty_fancy_raises(self, index):\n # DatetimeIndex is excluded, because it overrides getitem and should\n # be tested separately.\n empty_farr = np.array([], dtype=np.float_)\n empty_index = type(index)([])\n\n assert index[[]].identical(empty_index)\n # np.ndarray only accepts ndarray of int & bool dtypes, so should Index\n msg = r\"arrays used as indices must be of integer \\(or boolean\\) type\"\n with pytest.raises(IndexError, match=msg):\n index[empty_farr]\n\n def test_union_dt_as_obj(self, sort, simple_index):\n # TODO: Replace with fixturesult\n index = simple_index\n date_index = date_range(\"2019-01-01\", periods=10)\n first_cat = index.union(date_index)\n second_cat = index.union(index)\n\n appended = np.append(index, date_index.astype(\"O\"))\n\n assert tm.equalContents(first_cat, appended)\n assert tm.equalContents(second_cat, index)\n tm.assert_contains_all(index, first_cat)\n tm.assert_contains_all(index, second_cat)\n tm.assert_contains_all(date_index, first_cat)\n\n def test_map_with_tuples(self):\n # GH 12766\n\n # Test that returning a single tuple from an Index\n # returns an Index.\n index = tm.makeIntIndex(3)\n result = tm.makeIntIndex(3).map(lambda x: (x,))\n expected = Index([(i,) for i in index])\n tm.assert_index_equal(result, expected)\n\n # Test that returning a tuple from a map of a single index\n # returns a MultiIndex object.\n result = index.map(lambda x: (x, x == 1))\n expected = MultiIndex.from_tuples([(i, i == 1) for i in index])\n tm.assert_index_equal(result, expected)\n\n def test_map_with_tuples_mi(self):\n # Test that returning a single object from a MultiIndex\n # returns an Index.\n first_level = [\"foo\", \"bar\", \"baz\"]\n multi_index = MultiIndex.from_tuples(zip(first_level, [1, 2, 3]))\n reduced_index = multi_index.map(lambda x: x[0])\n tm.assert_index_equal(reduced_index, Index(first_level))\n\n @pytest.mark.parametrize(\n \"attr\", [\"makeDateIndex\", \"makePeriodIndex\", \"makeTimedeltaIndex\"]\n )\n def test_map_tseries_indices_return_index(self, attr):\n index = getattr(tm, attr)(10)\n expected = Index([1] * 10)\n result = index.map(lambda x: 1)\n tm.assert_index_equal(expected, result)\n\n def test_map_tseries_indices_accsr_return_index(self):\n date_index = tm.makeDateIndex(24, freq=\"h\", name=\"hourly\")\n expected = Index(range(24), name=\"hourly\")\n tm.assert_index_equal(expected, date_index.map(lambda x: x.hour))\n\n @pytest.mark.parametrize(\n \"mapper\",\n [\n lambda values, index: {i: e for e, i in zip(values, index)},\n lambda values, index: Series(values, index),\n ],\n )\n def test_map_dictlike_simple(self, mapper):\n # GH 12756\n expected = Index([\"foo\", \"bar\", \"baz\"])\n index = tm.makeIntIndex(3)\n result = index.map(mapper(expected.values, index))\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"mapper\",\n [\n lambda values, index: {i: e for e, i in zip(values, index)},\n lambda values, index: Series(values, index),\n ],\n )\n def test_map_dictlike(self, index, mapper):\n # GH 12756\n if isinstance(index, CategoricalIndex):\n # Tested in test_categorical\n return\n elif not index.is_unique:\n # Cannot map duplicated index\n return\n\n if index.empty:\n # to match proper result coercion for uints\n expected = Index([])\n else:\n expected = Index(np.arange(len(index), 0, -1))\n\n result = index.map(mapper(expected, index))\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"mapper\",\n [Series([\"foo\", 2.0, \"baz\"], index=[0, 2, -1]), {0: \"foo\", 2: 2.0, -1: \"baz\"}],\n )\n def test_map_with_non_function_missing_values(self, mapper):\n # GH 12756\n expected = Index([2.0, np.nan, \"foo\"])\n result = Index([2, 1, 0]).map(mapper)\n\n tm.assert_index_equal(expected, result)\n\n def test_map_na_exclusion(self):\n index = Index([1.5, np.nan, 3, np.nan, 5])\n\n result = index.map(lambda x: x * 2, na_action=\"ignore\")\n expected = index * 2\n tm.assert_index_equal(result, expected)\n\n def test_map_defaultdict(self):\n index = Index([1, 2, 3])\n default_dict = defaultdict(lambda: \"blank\")\n default_dict[1] = \"stuff\"\n result = index.map(default_dict)\n expected = Index([\"stuff\", \"blank\", \"blank\"])\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\"name,expected\", [(\"foo\", \"foo\"), (\"bar\", None)])\n def test_append_empty_preserve_name(self, name, expected):\n left = Index([], name=\"foo\")\n right = Index([1, 2, 3], name=name)\n\n result = left.append(right)\n assert result.name == expected\n\n def test_is_mixed_deprecated(self, simple_index):\n # GH#32922\n index = simple_index\n with tm.assert_produces_warning(FutureWarning):\n index.is_mixed()\n\n @pytest.mark.parametrize(\n \"index, expected\",\n [\n (\"string\", False),\n (\"bool\", False),\n (\"categorical\", False),\n (\"int\", True),\n (\"datetime\", False),\n (\"float\", True),\n ],\n indirect=[\"index\"],\n )\n def test_is_numeric(self, index, expected):\n assert index.is_numeric() is expected\n\n @pytest.mark.parametrize(\n \"index, expected\",\n [\n (\"string\", True),\n (\"bool\", True),\n (\"categorical\", False),\n (\"int\", False),\n (\"datetime\", False),\n (\"float\", False),\n ],\n indirect=[\"index\"],\n )\n def test_is_object(self, index, expected):\n assert index.is_object() is expected\n\n @pytest.mark.parametrize(\n \"index, expected\",\n [\n (\"string\", False),\n (\"bool\", False),\n (\"categorical\", False),\n (\"int\", False),\n (\"datetime\", True),\n (\"float\", False),\n ],\n indirect=[\"index\"],\n )\n def test_is_all_dates(self, index, expected):\n with tm.assert_produces_warning(FutureWarning):\n assert index.is_all_dates is expected\n\n def test_summary(self, index):\n index._summary()\n\n def test_summary_bug(self):\n # GH3869`\n ind = Index([\"{other}%s\", \"~:{range}:0\"], name=\"A\")\n result = ind._summary()\n # shouldn't be formatted accidentally.\n assert \"~:{range}:0\" in result\n assert \"{other}%s\" in result\n\n def test_format_different_scalar_lengths(self):\n # GH35439\n idx = Index([\"aaaaaaaaa\", \"b\"])\n expected = [\"aaaaaaaaa\", \"b\"]\n assert idx.format() == expected\n\n def test_format_bug(self):\n # GH 14626\n # windows has different precision on datetime.datetime.now (it doesn't\n # include us since the default for Timestamp shows these but Index\n # formatting does not we are skipping)\n now = datetime.now()\n if not str(now).endswith(\"000\"):\n index = Index([now])\n formatted = index.format()\n expected = [str(index[0])]\n assert formatted == expected\n\n Index([]).format()\n\n @pytest.mark.parametrize(\"vals\", [[1, 2.0 + 3.0j, 4.0], [\"a\", \"b\", \"c\"]])\n def test_format_missing(self, vals, nulls_fixture):\n # 2845\n vals = list(vals) # Copy for each iteration\n vals.append(nulls_fixture)\n index = Index(vals)\n\n formatted = index.format()\n expected = [str(index[0]), str(index[1]), str(index[2]), \"NaN\"]\n\n assert formatted == expected\n assert index[3] is nulls_fixture\n\n def test_format_with_name_time_info(self):\n # bug I fixed 12/20/2011\n dates = date_range(\"2011-01-01 04:00:00\", periods=10, name=\"something\")\n\n formatted = dates.format(name=True)\n assert formatted[0] == \"something\"\n\n def test_format_datetime_with_time(self):\n t = Index([datetime(2012, 2, 7), datetime(2012, 2, 7, 23)])\n\n result = t.format()\n expected = [\"2012-02-07 00:00:00\", \"2012-02-07 23:00:00\"]\n assert len(result) == 2\n assert result == expected\n\n @pytest.mark.parametrize(\"op\", [\"any\", \"all\"])\n def test_logical_compat(self, op, simple_index):\n index = simple_index\n assert getattr(index, op)() == getattr(index.values, op)()\n\n @pytest.mark.parametrize(\"index\", [\"string\", \"int\", \"float\"], indirect=True)\n def test_drop_by_str_label(self, index):\n n = len(index)\n drop = index[list(range(5, 10))]\n dropped = index.drop(drop)\n\n expected = index[list(range(5)) + list(range(10, n))]\n tm.assert_index_equal(dropped, expected)\n\n dropped = index.drop(index[0])\n expected = index[1:]\n tm.assert_index_equal(dropped, expected)\n\n @pytest.mark.parametrize(\"index\", [\"string\", \"int\", \"float\"], indirect=True)\n @pytest.mark.parametrize(\"keys\", [[\"foo\", \"bar\"], [\"1\", \"bar\"]])\n def test_drop_by_str_label_raises_missing_keys(self, index, keys):\n with pytest.raises(KeyError, match=\"\"):\n index.drop(keys)\n\n @pytest.mark.parametrize(\"index\", [\"string\", \"int\", \"float\"], indirect=True)\n def test_drop_by_str_label_errors_ignore(self, index):\n n = len(index)\n drop = index[list(range(5, 10))]\n mixed = drop.tolist() + [\"foo\"]\n dropped = index.drop(mixed, errors=\"ignore\")\n\n expected = index[list(range(5)) + list(range(10, n))]\n tm.assert_index_equal(dropped, expected)\n\n dropped = index.drop([\"foo\", \"bar\"], errors=\"ignore\")\n expected = index[list(range(n))]\n tm.assert_index_equal(dropped, expected)\n\n def test_drop_by_numeric_label_loc(self):\n # TODO: Parametrize numeric and str tests after self.strIndex fixture\n index = Index([1, 2, 3])\n dropped = index.drop(1)\n expected = Index([2, 3])\n\n tm.assert_index_equal(dropped, expected)\n\n def test_drop_by_numeric_label_raises_missing_keys(self):\n index = Index([1, 2, 3])\n with pytest.raises(KeyError, match=\"\"):\n index.drop([3, 4])\n\n @pytest.mark.parametrize(\n \"key,expected\", [(4, Index([1, 2, 3])), ([3, 4, 5], Index([1, 2]))]\n )\n def test_drop_by_numeric_label_errors_ignore(self, key, expected):\n index = Index([1, 2, 3])\n dropped = index.drop(key, errors=\"ignore\")\n\n tm.assert_index_equal(dropped, expected)\n\n @pytest.mark.parametrize(\n \"values\",\n [[\"a\", \"b\", (\"c\", \"d\")], [\"a\", (\"c\", \"d\"), \"b\"], [(\"c\", \"d\"), \"a\", \"b\"]],\n )\n @pytest.mark.parametrize(\"to_drop\", [[(\"c\", \"d\"), \"a\"], [\"a\", (\"c\", \"d\")]])\n def test_drop_tuple(self, values, to_drop):\n # GH 18304\n index = Index(values)\n expected = Index([\"b\"])\n\n result = index.drop(to_drop)\n tm.assert_index_equal(result, expected)\n\n removed = index.drop(to_drop[0])\n for drop_me in to_drop[1], [to_drop[1]]:\n result = removed.drop(drop_me)\n tm.assert_index_equal(result, expected)\n\n removed = index.drop(to_drop[1])\n msg = fr\"\\\"\\[{re.escape(to_drop[1].__repr__())}\\] not found in axis\\\"\"\n for drop_me in to_drop[1], [to_drop[1]]:\n with pytest.raises(KeyError, match=msg):\n removed.drop(drop_me)\n\n def test_drop_with_duplicates_in_index(self, index):\n # GH38051\n if len(index) == 0 or isinstance(index, MultiIndex):\n return\n if isinstance(index, IntervalIndex) and not IS64:\n pytest.skip(\"Cannot test IntervalIndex with int64 dtype on 32 bit platform\")\n index = index.unique().repeat(2)\n expected = index[2:]\n result = index.drop(index[0])\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"attr\",\n [\n \"is_monotonic_increasing\",\n \"is_monotonic_decreasing\",\n \"_is_strictly_monotonic_increasing\",\n \"_is_strictly_monotonic_decreasing\",\n ],\n )\n def test_is_monotonic_incomparable(self, attr):\n index = Index([5, datetime.now(), 7])\n assert not getattr(index, attr)\n\n def test_set_value_deprecated(self, simple_index):\n # GH 28621\n idx = simple_index\n arr = np.array([1, 2, 3])\n with tm.assert_produces_warning(FutureWarning):\n idx.set_value(arr, idx[1], 80)\n assert arr[1] == 80\n\n @pytest.mark.parametrize(\"values\", [[\"foo\", \"bar\", \"quux\"], {\"foo\", \"bar\", \"quux\"}])\n @pytest.mark.parametrize(\n \"index,expected\",\n [\n (Index([\"qux\", \"baz\", \"foo\", \"bar\"]), np.array([False, False, True, True])),\n (Index([]), np.array([], dtype=bool)), # empty\n ],\n )\n def test_isin(self, values, index, expected):\n result = index.isin(values)\n tm.assert_numpy_array_equal(result, expected)\n\n def test_isin_nan_common_object(self, nulls_fixture, nulls_fixture2):\n # Test cartesian product of null fixtures and ensure that we don't\n # mangle the various types (save a corner case with PyPy)\n\n # all nans are the same\n if (\n isinstance(nulls_fixture, float)\n and isinstance(nulls_fixture2, float)\n and math.isnan(nulls_fixture)\n and math.isnan(nulls_fixture2)\n ):\n tm.assert_numpy_array_equal(\n Index([\"a\", nulls_fixture]).isin([nulls_fixture2]),\n np.array([False, True]),\n )\n\n elif nulls_fixture is nulls_fixture2: # should preserve NA type\n tm.assert_numpy_array_equal(\n Index([\"a\", nulls_fixture]).isin([nulls_fixture2]),\n np.array([False, True]),\n )\n\n else:\n tm.assert_numpy_array_equal(\n Index([\"a\", nulls_fixture]).isin([nulls_fixture2]),\n np.array([False, False]),\n )\n\n def test_isin_nan_common_float64(self, request, nulls_fixture):\n if nulls_fixture is pd.NaT:\n pytest.skip(\"pd.NaT not compatible with Float64Index\")\n\n # Float64Index overrides isin, so must be checked separately\n if nulls_fixture is pd.NA:\n request.node.add_marker(\n pytest.mark.xfail(reason=\"Float64Index cannot contain pd.NA\")\n )\n\n tm.assert_numpy_array_equal(\n Float64Index([1.0, nulls_fixture]).isin([np.nan]), np.array([False, True])\n )\n\n # we cannot compare NaT with NaN\n tm.assert_numpy_array_equal(\n Float64Index([1.0, nulls_fixture]).isin([pd.NaT]), np.array([False, False])\n )\n\n @pytest.mark.parametrize(\"level\", [0, -1])\n @pytest.mark.parametrize(\n \"index\",\n [\n Index([\"qux\", \"baz\", \"foo\", \"bar\"]),\n # Float64Index overrides isin, so must be checked separately\n Float64Index([1.0, 2.0, 3.0, 4.0]),\n ],\n )\n def test_isin_level_kwarg(self, level, index):\n values = index.tolist()[-2:] + [\"nonexisting\"]\n\n expected = np.array([False, False, True, True])\n tm.assert_numpy_array_equal(expected, index.isin(values, level=level))\n\n index.name = \"foobar\"\n tm.assert_numpy_array_equal(expected, index.isin(values, level=\"foobar\"))\n\n def test_isin_level_kwarg_bad_level_raises(self, index):\n for level in [10, index.nlevels, -(index.nlevels + 1)]:\n with pytest.raises(IndexError, match=\"Too many levels\"):\n index.isin([], level=level)\n\n @pytest.mark.parametrize(\"label\", [1.0, \"foobar\", \"xyzzy\", np.nan])\n def test_isin_level_kwarg_bad_label_raises(self, label, index):\n if isinstance(index, MultiIndex):\n index = index.rename([\"foo\", \"bar\"] + index.names[2:])\n msg = f\"'Level {label} not found'\"\n else:\n index = index.rename(\"foo\")\n msg = fr\"Requested level \\({label}\\) does not match index name \\(foo\\)\"\n with pytest.raises(KeyError, match=msg):\n index.isin([], level=label)\n\n @pytest.mark.parametrize(\"empty\", [[], Series(dtype=object), np.array([])])\n def test_isin_empty(self, empty):\n # see gh-16991\n index = Index([\"a\", \"b\"])\n expected = np.array([False, False])\n\n result = index.isin(empty)\n tm.assert_numpy_array_equal(expected, result)\n\n @pytest.mark.parametrize(\n \"values\",\n [\n [1, 2, 3, 4],\n [1.0, 2.0, 3.0, 4.0],\n [True, True, True, True],\n [\"foo\", \"bar\", \"baz\", \"qux\"],\n date_range(\"2018-01-01\", freq=\"D\", periods=4),\n ],\n )\n def test_boolean_cmp(self, values):\n index = Index(values)\n result = index == values\n expected = np.array([True, True, True, True], dtype=bool)\n\n tm.assert_numpy_array_equal(result, expected)\n\n @pytest.mark.parametrize(\"index\", [\"string\"], indirect=True)\n @pytest.mark.parametrize(\"name,level\", [(None, 0), (\"a\", \"a\")])\n def test_get_level_values(self, index, name, level):\n expected = index.copy()\n if name:\n expected.name = name\n\n result = expected.get_level_values(level)\n tm.assert_index_equal(result, expected)\n\n def test_slice_keep_name(self):\n index = Index([\"a\", \"b\"], name=\"asdf\")\n assert index.name == index[1:].name\n\n @pytest.mark.parametrize(\n \"index\",\n [\"unicode\", \"string\", \"datetime\", \"int\", \"uint\", \"float\"],\n indirect=True,\n )\n def test_join_self(self, index, join_type):\n joined = index.join(index, how=join_type)\n assert index is joined\n\n @pytest.mark.parametrize(\"method\", [\"strip\", \"rstrip\", \"lstrip\"])\n def test_str_attribute(self, method):\n # GH9068\n index = Index([\" jack\", \"jill \", \" jesse \", \"frank\"])\n expected = Index([getattr(str, method)(x) for x in index.values])\n\n result = getattr(index.str, method)()\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"index\",\n [\n Index(range(5)),\n tm.makeDateIndex(10),\n MultiIndex.from_tuples([(\"foo\", \"1\"), (\"bar\", \"3\")]),\n period_range(start=\"2000\", end=\"2010\", freq=\"A\"),\n ],\n )\n def test_str_attribute_raises(self, index):\n with pytest.raises(AttributeError, match=\"only use .str accessor\"):\n index.str.repeat(2)\n\n @pytest.mark.parametrize(\n \"expand,expected\",\n [\n (None, Index([[\"a\", \"b\", \"c\"], [\"d\", \"e\"], [\"f\"]])),\n (False, Index([[\"a\", \"b\", \"c\"], [\"d\", \"e\"], [\"f\"]])),\n (\n True,\n MultiIndex.from_tuples(\n [(\"a\", \"b\", \"c\"), (\"d\", \"e\", np.nan), (\"f\", np.nan, np.nan)]\n ),\n ),\n ],\n )\n def test_str_split(self, expand, expected):\n index = Index([\"a b c\", \"d e\", \"f\"])\n if expand is not None:\n result = index.str.split(expand=expand)\n else:\n result = index.str.split()\n\n tm.assert_index_equal(result, expected)\n\n def test_str_bool_return(self):\n # test boolean case, should return np.array instead of boolean Index\n index = Index([\"a1\", \"a2\", \"b1\", \"b2\"])\n result = index.str.startswith(\"a\")\n expected = np.array([True, True, False, False])\n\n tm.assert_numpy_array_equal(result, expected)\n assert isinstance(result, np.ndarray)\n\n def test_str_bool_series_indexing(self):\n index = Index([\"a1\", \"a2\", \"b1\", \"b2\"])\n s = Series(range(4), index=index)\n\n result = s[s.index.str.startswith(\"a\")]\n expected = Series(range(2), index=[\"a1\", \"a2\"])\n tm.assert_series_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"index,expected\", [(Index(list(\"abcd\")), True), (Index(range(4)), False)]\n )\n def test_tab_completion(self, index, expected):\n # GH 9910\n result = \"str\" in dir(index)\n assert result == expected\n\n def test_indexing_doesnt_change_class(self):\n index = Index([1, 2, 3, \"a\", \"b\", \"c\"])\n\n assert index[1:3].identical(Index([2, 3], dtype=np.object_))\n assert index[[0, 1]].identical(Index([1, 2], dtype=np.object_))\n\n def test_outer_join_sort(self):\n left_index = Index(np.random.permutation(15))\n right_index = tm.makeDateIndex(10)\n\n with tm.assert_produces_warning(RuntimeWarning):\n result = left_index.join(right_index, how=\"outer\")\n\n # right_index in this case because DatetimeIndex has join precedence\n # over Int64Index\n with tm.assert_produces_warning(RuntimeWarning):\n expected = right_index.astype(object).union(left_index.astype(object))\n\n tm.assert_index_equal(result, expected)\n\n def test_nan_first_take_datetime(self):\n index = Index([pd.NaT, Timestamp(\"20130101\"), Timestamp(\"20130102\")])\n result = index.take([-1, 0, 1])\n expected = Index([index[-1], index[0], index[1]])\n tm.assert_index_equal(result, expected)\n\n def test_take_fill_value(self):\n # GH 12631\n index = Index(list(\"ABC\"), name=\"xxx\")\n result = index.take(np.array([1, 0, -1]))\n expected = Index(list(\"BAC\"), name=\"xxx\")\n tm.assert_index_equal(result, expected)\n\n # fill_value\n result = index.take(np.array([1, 0, -1]), fill_value=True)\n expected = Index([\"B\", \"A\", np.nan], name=\"xxx\")\n tm.assert_index_equal(result, expected)\n\n # allow_fill=False\n result = index.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)\n expected = Index([\"B\", \"A\", \"C\"], name=\"xxx\")\n tm.assert_index_equal(result, expected)\n\n def test_take_fill_value_none_raises(self):\n index = Index(list(\"ABC\"), name=\"xxx\")\n msg = (\n \"When allow_fill=True and fill_value is not None, \"\n \"all indices must be >= -1\"\n )\n\n with pytest.raises(ValueError, match=msg):\n index.take(np.array([1, 0, -2]), fill_value=True)\n with pytest.raises(ValueError, match=msg):\n index.take(np.array([1, 0, -5]), fill_value=True)\n\n def test_take_bad_bounds_raises(self):\n index = Index(list(\"ABC\"), name=\"xxx\")\n with pytest.raises(IndexError, match=\"out of bounds\"):\n index.take(np.array([1, -5]))\n\n @pytest.mark.parametrize(\"name\", [None, \"foobar\"])\n @pytest.mark.parametrize(\n \"labels\",\n [\n [],\n np.array([]),\n [\"A\", \"B\", \"C\"],\n [\"C\", \"B\", \"A\"],\n np.array([\"A\", \"B\", \"C\"]),\n np.array([\"C\", \"B\", \"A\"]),\n # Must preserve name even if dtype changes\n date_range(\"20130101\", periods=3).values,\n date_range(\"20130101\", periods=3).tolist(),\n ],\n )\n def test_reindex_preserves_name_if_target_is_list_or_ndarray(self, name, labels):\n # GH6552\n index = Index([0, 1, 2])\n index.name = name\n assert index.reindex(labels)[0].name == name\n\n @pytest.mark.parametrize(\"labels\", [[], np.array([]), np.array([], dtype=np.int64)])\n def test_reindex_preserves_type_if_target_is_empty_list_or_array(self, labels):\n # GH7774\n index = Index(list(\"abc\"))\n assert index.reindex(labels)[0].dtype.type == np.object_\n\n @pytest.mark.parametrize(\n \"labels,dtype\",\n [\n (Int64Index([]), np.int64),\n (Float64Index([]), np.float64),\n (DatetimeIndex([]), np.datetime64),\n ],\n )\n def test_reindex_doesnt_preserve_type_if_target_is_empty_index(self, labels, dtype):\n # GH7774\n index = Index(list(\"abc\"))\n assert index.reindex(labels)[0].dtype.type == dtype\n\n def test_reindex_no_type_preserve_target_empty_mi(self):\n index = Index(list(\"abc\"))\n result = index.reindex(\n MultiIndex([Int64Index([]), Float64Index([])], [[], []])\n )[0]\n assert result.levels[0].dtype.type == np.int64\n assert result.levels[1].dtype.type == np.float64\n\n def test_groupby(self):\n index = Index(range(5))\n result = index.groupby(np.array([1, 1, 2, 2, 2]))\n expected = {1: Index([0, 1]), 2: Index([2, 3, 4])}\n\n tm.assert_dict_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"mi,expected\",\n [\n (MultiIndex.from_tuples([(1, 2), (4, 5)]), np.array([True, True])),\n (MultiIndex.from_tuples([(1, 2), (4, 6)]), np.array([True, False])),\n ],\n )\n def test_equals_op_multiindex(self, mi, expected):\n # GH9785\n # test comparisons of multiindex\n df = pd.read_csv(StringIO(\"a,b,c\\n1,2,3\\n4,5,6\"), index_col=[0, 1])\n\n result = df.index == mi\n tm.assert_numpy_array_equal(result, expected)\n\n def test_equals_op_multiindex_identify(self):\n df = pd.read_csv(StringIO(\"a,b,c\\n1,2,3\\n4,5,6\"), index_col=[0, 1])\n\n result = df.index == df.index\n expected = np.array([True, True])\n tm.assert_numpy_array_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"index\",\n [\n MultiIndex.from_tuples([(1, 2), (4, 5), (8, 9)]),\n Index([\"foo\", \"bar\", \"baz\"]),\n ],\n )\n def test_equals_op_mismatched_multiindex_raises(self, index):\n df = pd.read_csv(StringIO(\"a,b,c\\n1,2,3\\n4,5,6\"), index_col=[0, 1])\n\n with pytest.raises(ValueError, match=\"Lengths must match\"):\n df.index == index\n\n def test_equals_op_index_vs_mi_same_length(self):\n mi = MultiIndex.from_tuples([(1, 2), (4, 5), (8, 9)])\n index = Index([\"foo\", \"bar\", \"baz\"])\n\n result = mi == index\n expected = np.array([False, False, False])\n tm.assert_numpy_array_equal(result, expected)\n\n @pytest.mark.parametrize(\"dt_conv\", [pd.to_datetime, pd.to_timedelta])\n def test_dt_conversion_preserves_name(self, dt_conv):\n # GH 10875\n index = Index([\"01:02:03\", \"01:02:04\"], name=\"label\")\n assert index.name == dt_conv(index).name\n\n def test_cached_properties_not_settable(self):\n index = Index([1, 2, 3])\n with pytest.raises(AttributeError, match=\"Can't set attribute\"):\n index.is_unique = False\n\n @async_mark()\n async def test_tab_complete_warning(self, ip):\n # https://github.com/pandas-dev/pandas/issues/16409\n pytest.importorskip(\"IPython\", minversion=\"6.0.0\")\n from IPython.core.completer import provisionalcompleter\n\n code = \"import pandas as pd; idx = pd.Index([1, 2])\"\n await ip.run_code(code)\n\n # GH 31324 newer jedi version raises Deprecation warning;\n # appears resolved 2021-02-02\n with tm.assert_produces_warning(None):\n with provisionalcompleter(\"ignore\"):\n list(ip.Completer.completions(\"idx.\", 4))\n\n def test_contains_method_removed(self, index):\n # GH#30103 method removed for all types except IntervalIndex\n if isinstance(index, IntervalIndex):\n index.contains(1)\n else:\n msg = f\"'{type(index).__name__}' object has no attribute 'contains'\"\n with pytest.raises(AttributeError, match=msg):\n index.contains(1)\n\n def test_sortlevel(self):\n index = Index([5, 4, 3, 2, 1])\n with pytest.raises(Exception, match=\"ascending must be a single bool value or\"):\n index.sortlevel(ascending=\"True\")\n\n with pytest.raises(\n Exception, match=\"ascending must be a list of bool values of length 1\"\n ):\n index.sortlevel(ascending=[True, True])\n\n with pytest.raises(Exception, match=\"ascending must be a bool value\"):\n index.sortlevel(ascending=[\"True\"])\n\n expected = Index([1, 2, 3, 4, 5])\n result = index.sortlevel(ascending=[True])\n tm.assert_index_equal(result[0], expected)\n\n expected = Index([1, 2, 3, 4, 5])\n result = index.sortlevel(ascending=True)\n tm.assert_index_equal(result[0], expected)\n\n expected = Index([5, 4, 3, 2, 1])\n result = index.sortlevel(ascending=False)\n tm.assert_index_equal(result[0], expected)\n\n\nclass TestMixedIntIndex(Base):\n # Mostly the tests from common.py for which the results differ\n # in py2 and py3 because ints and strings are uncomparable in py3\n # (GH 13514)\n _index_cls = Index\n\n @pytest.fixture\n def simple_index(self) -> Index:\n return self._index_cls([0, \"a\", 1, \"b\", 2, \"c\"])\n\n @pytest.fixture(params=[[0, \"a\", 1, \"b\", 2, \"c\"]], ids=[\"mixedIndex\"])\n def index(self, request):\n return Index(request.param)\n\n def test_argsort(self, simple_index):\n index = simple_index\n with pytest.raises(TypeError, match=\"'>|<' not supported\"):\n index.argsort()\n\n def test_numpy_argsort(self, simple_index):\n index = simple_index\n with pytest.raises(TypeError, match=\"'>|<' not supported\"):\n np.argsort(index)\n\n def test_copy_name(self, simple_index):\n # Check that \"name\" argument passed at initialization is honoured\n # GH12309\n index = simple_index\n\n first = type(index)(index, copy=True, name=\"mario\")\n second = type(first)(first, copy=False)\n\n # Even though \"copy=False\", we want a new object.\n assert first is not second\n tm.assert_index_equal(first, second)\n\n assert first.name == \"mario\"\n assert second.name == \"mario\"\n\n s1 = Series(2, index=first)\n s2 = Series(3, index=second[:-1])\n\n s3 = s1 * s2\n\n assert s3.index.name == \"mario\"\n\n def test_copy_name2(self):\n # Check that adding a \"name\" parameter to the copy is honored\n # GH14302\n index = Index([1, 2], name=\"MyName\")\n index1 = index.copy()\n\n tm.assert_index_equal(index, index1)\n\n index2 = index.copy(name=\"NewName\")\n tm.assert_index_equal(index, index2, check_names=False)\n assert index.name == \"MyName\"\n assert index2.name == \"NewName\"\n\n index3 = index.copy(names=[\"NewName\"])\n tm.assert_index_equal(index, index3, check_names=False)\n assert index.name == \"MyName\"\n assert index.names == [\"MyName\"]\n assert index3.name == \"NewName\"\n assert index3.names == [\"NewName\"]\n\n def test_unique_na(self):\n idx = Index([2, np.nan, 2, 1], name=\"my_index\")\n expected = Index([2, np.nan, 1], name=\"my_index\")\n result = idx.unique()\n tm.assert_index_equal(result, expected)\n\n def test_logical_compat(self, simple_index):\n index = simple_index\n assert index.all() == index.values.all()\n assert index.any() == index.values.any()\n\n @pytest.mark.parametrize(\"how\", [\"any\", \"all\"])\n @pytest.mark.parametrize(\"dtype\", [None, object, \"category\"])\n @pytest.mark.parametrize(\n \"vals,expected\",\n [\n ([1, 2, 3], [1, 2, 3]),\n ([1.0, 2.0, 3.0], [1.0, 2.0, 3.0]),\n ([1.0, 2.0, np.nan, 3.0], [1.0, 2.0, 3.0]),\n ([\"A\", \"B\", \"C\"], [\"A\", \"B\", \"C\"]),\n ([\"A\", np.nan, \"B\", \"C\"], [\"A\", \"B\", \"C\"]),\n ],\n )\n def test_dropna(self, how, dtype, vals, expected):\n # GH 6194\n index = Index(vals, dtype=dtype)\n result = index.dropna(how=how)\n expected = Index(expected, dtype=dtype)\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\"how\", [\"any\", \"all\"])\n @pytest.mark.parametrize(\n \"index,expected\",\n [\n (\n DatetimeIndex([\"2011-01-01\", \"2011-01-02\", \"2011-01-03\"]),\n DatetimeIndex([\"2011-01-01\", \"2011-01-02\", \"2011-01-03\"]),\n ),\n (\n DatetimeIndex([\"2011-01-01\", \"2011-01-02\", \"2011-01-03\", pd.NaT]),\n DatetimeIndex([\"2011-01-01\", \"2011-01-02\", \"2011-01-03\"]),\n ),\n (\n TimedeltaIndex([\"1 days\", \"2 days\", \"3 days\"]),\n TimedeltaIndex([\"1 days\", \"2 days\", \"3 days\"]),\n ),\n (\n TimedeltaIndex([pd.NaT, \"1 days\", \"2 days\", \"3 days\", pd.NaT]),\n TimedeltaIndex([\"1 days\", \"2 days\", \"3 days\"]),\n ),\n (\n PeriodIndex([\"2012-02\", \"2012-04\", \"2012-05\"], freq=\"M\"),\n PeriodIndex([\"2012-02\", \"2012-04\", \"2012-05\"], freq=\"M\"),\n ),\n (\n PeriodIndex([\"2012-02\", \"2012-04\", \"NaT\", \"2012-05\"], freq=\"M\"),\n PeriodIndex([\"2012-02\", \"2012-04\", \"2012-05\"], freq=\"M\"),\n ),\n ],\n )\n def test_dropna_dt_like(self, how, index, expected):\n result = index.dropna(how=how)\n tm.assert_index_equal(result, expected)\n\n def test_dropna_invalid_how_raises(self):\n msg = \"invalid how option: xxx\"\n with pytest.raises(ValueError, match=msg):\n Index([1, 2, 3]).dropna(how=\"xxx\")\n\n @pytest.mark.parametrize(\n \"index\",\n [\n Index([np.nan]),\n Index([np.nan, 1]),\n Index([1, 2, np.nan]),\n Index([\"a\", \"b\", np.nan]),\n pd.to_datetime([\"NaT\"]),\n pd.to_datetime([\"NaT\", \"2000-01-01\"]),\n pd.to_datetime([\"2000-01-01\", \"NaT\", \"2000-01-02\"]),\n pd.to_timedelta([\"1 day\", \"NaT\"]),\n ],\n )\n def test_is_monotonic_na(self, index):\n assert index.is_monotonic_increasing is False\n assert index.is_monotonic_decreasing is False\n assert index._is_strictly_monotonic_increasing is False\n assert index._is_strictly_monotonic_decreasing is False\n\n @pytest.mark.parametrize(\"klass\", [Series, DataFrame])\n def test_int_name_format(self, klass):\n index = Index([\"a\", \"b\", \"c\"], name=0)\n result = klass(list(range(3)), index=index)\n assert \"0\" in repr(result)\n\n def test_str_to_bytes_raises(self):\n # GH 26447\n index = Index([str(x) for x in range(10)])\n msg = \"^'str' object cannot be interpreted as an integer$\"\n with pytest.raises(TypeError, match=msg):\n bytes(index)\n\n @pytest.mark.filterwarnings(\"ignore:elementwise comparison failed:FutureWarning\")\n def test_index_with_tuple_bool(self):\n # GH34123\n # TODO: remove tupleize_cols=False once correct behaviour is restored\n # TODO: also this op right now produces FutureWarning from numpy\n idx = Index([(\"a\", \"b\"), (\"b\", \"c\"), (\"c\", \"a\")], tupleize_cols=False)\n result = idx == (\"c\", \"a\")\n expected = np.array([False, False, True])\n tm.assert_numpy_array_equal(result, expected)\n\n\nclass TestIndexUtils:\n @pytest.mark.parametrize(\n \"data, names, expected\",\n [\n ([[1, 2, 3]], None, Index([1, 2, 3])),\n ([[1, 2, 3]], [\"name\"], Index([1, 2, 3], name=\"name\")),\n (\n [[\"a\", \"a\"], [\"c\", \"d\"]],\n None,\n MultiIndex([[\"a\"], [\"c\", \"d\"]], [[0, 0], [0, 1]]),\n ),\n (\n [[\"a\", \"a\"], [\"c\", \"d\"]],\n [\"L1\", \"L2\"],\n MultiIndex([[\"a\"], [\"c\", \"d\"]], [[0, 0], [0, 1]], names=[\"L1\", \"L2\"]),\n ),\n ],\n )\n def test_ensure_index_from_sequences(self, data, names, expected):\n result = ensure_index_from_sequences(data, names)\n tm.assert_index_equal(result, expected)\n\n def test_ensure_index_mixed_closed_intervals(self):\n # GH27172\n intervals = [\n pd.Interval(0, 1, closed=\"left\"),\n pd.Interval(1, 2, closed=\"right\"),\n pd.Interval(2, 3, closed=\"neither\"),\n pd.Interval(3, 4, closed=\"both\"),\n ]\n result = ensure_index(intervals)\n expected = Index(intervals, dtype=object)\n tm.assert_index_equal(result, expected)\n\n def test_get_combined_index(self):\n result = _get_combined_index([])\n expected = Index([])\n tm.assert_index_equal(result, expected)\n\n\[email protected](\n \"opname\",\n [\n \"eq\",\n \"ne\",\n \"le\",\n \"lt\",\n \"ge\",\n \"gt\",\n \"add\",\n \"radd\",\n \"sub\",\n \"rsub\",\n \"mul\",\n \"rmul\",\n \"truediv\",\n \"rtruediv\",\n \"floordiv\",\n \"rfloordiv\",\n \"pow\",\n \"rpow\",\n \"mod\",\n \"divmod\",\n ],\n)\ndef test_generated_op_names(opname, index):\n opname = f\"__{opname}__\"\n method = getattr(index, opname)\n assert method.__name__ == opname\n\n\[email protected](\"index_maker\", tm.index_subclass_makers_generator())\ndef test_index_subclass_constructor_wrong_kwargs(index_maker):\n # GH #19348\n with pytest.raises(TypeError, match=\"unexpected keyword argument\"):\n index_maker(foo=\"bar\")\n\n\[email protected](\"ignore:Passing keywords other:FutureWarning\")\ndef test_deprecated_fastpath():\n msg = \"[Uu]nexpected keyword argument\"\n with pytest.raises(TypeError, match=msg):\n Index(np.array([\"a\", \"b\"], dtype=object), name=\"test\", fastpath=True)\n\n with pytest.raises(TypeError, match=msg):\n Int64Index(np.array([1, 2, 3], dtype=\"int64\"), name=\"test\", fastpath=True)\n\n with pytest.raises(TypeError, match=msg):\n RangeIndex(0, 5, 2, name=\"test\", fastpath=True)\n\n with pytest.raises(TypeError, match=msg):\n CategoricalIndex([\"a\", \"b\", \"c\"], name=\"test\", fastpath=True)\n\n\ndef test_shape_of_invalid_index():\n # Currently, it is possible to create \"invalid\" index objects backed by\n # a multi-dimensional array (see https://github.com/pandas-dev/pandas/issues/27125\n # about this). However, as long as this is not solved in general,this test ensures\n # that the returned shape is consistent with this underlying array for\n # compat with matplotlib (see https://github.com/pandas-dev/pandas/issues/27775)\n idx = Index([0, 1, 2, 3])\n with tm.assert_produces_warning(FutureWarning):\n # GH#30588 multi-dimensional indexing deprecated\n assert idx[:, None].shape == (4, 1)\n\n\ndef test_validate_1d_input():\n # GH#27125 check that we do not have >1-dimensional input\n msg = \"Index data must be 1-dimensional\"\n\n arr = np.arange(8).reshape(2, 2, 2)\n with pytest.raises(ValueError, match=msg):\n Index(arr)\n\n with pytest.raises(ValueError, match=msg):\n Float64Index(arr.astype(np.float64))\n\n with pytest.raises(ValueError, match=msg):\n Int64Index(arr.astype(np.int64))\n\n with pytest.raises(ValueError, match=msg):\n UInt64Index(arr.astype(np.uint64))\n\n df = DataFrame(arr.reshape(4, 2))\n with pytest.raises(ValueError, match=msg):\n Index(df)\n\n # GH#13601 trying to assign a multi-dimensional array to an index is not\n # allowed\n ser = Series(0, range(4))\n with pytest.raises(ValueError, match=msg):\n ser.index = np.array([[2, 3]] * 4)\n\n\[email protected](\n \"klass, extra_kwargs\",\n [\n [Index, {}],\n [Int64Index, {}],\n [Float64Index, {}],\n [DatetimeIndex, {}],\n [TimedeltaIndex, {}],\n [PeriodIndex, {\"freq\": \"Y\"}],\n ],\n)\ndef test_construct_from_memoryview(klass, extra_kwargs):\n # GH 13120\n result = klass(memoryview(np.arange(2000, 2005)), **extra_kwargs)\n expected = klass(range(2000, 2005), **extra_kwargs)\n tm.assert_index_equal(result, expected)\n\n\ndef test_index_set_names_pos_args_deprecation():\n # GH#41485\n idx = Index([1, 2, 3, 4])\n msg = (\n \"In a future version of pandas all arguments of Index.set_names \"\n \"except for the argument 'names' will be keyword-only\"\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = idx.set_names(\"quarter\", None)\n expected = Index([1, 2, 3, 4], name=\"quarter\")\n tm.assert_index_equal(result, expected)\n\n\ndef test_drop_duplicates_pos_args_deprecation():\n # GH#41485\n idx = Index([1, 2, 3, 1])\n msg = (\n \"In a future version of pandas all arguments of \"\n \"Index.drop_duplicates will be keyword-only\"\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n idx.drop_duplicates(\"last\")\n result = idx.drop_duplicates(\"last\")\n expected = Index([2, 3, 1])\n tm.assert_index_equal(expected, result)\n"
] | [
[
"pandas._testing.assert_numpy_array_equal",
"pandas.timedelta_range",
"pandas.Series",
"pandas.CategoricalIndex",
"pandas.core.indexes.api.ensure_index_from_sequences",
"numpy.argsort",
"pandas.Float64Index",
"pandas._testing.assert_series_equal",
"pandas.RangeIndex",
"pandas.core.indexes.api.MultiIndex.from_tuples",
"pandas.core.indexes.api._get_combined_index",
"pandas._testing.makeDateIndex",
"pandas.period_range",
"pandas.PeriodIndex",
"pandas.core.indexes.api.ensure_index",
"numpy.timedelta64",
"pandas._testing.assert_produces_warning",
"pandas._testing.assert_contains_all",
"pandas.to_datetime",
"numpy.random.rand",
"pandas.core.indexes.api.Index",
"pandas.to_timedelta",
"pandas.Timestamp",
"pandas._testing.assert_dict_equal",
"pandas.date_range",
"pandas.compat.np_datetime64_compat",
"pandas._testing.equalContents",
"pandas.core.indexes.api.MultiIndex",
"pandas.Timedelta",
"numpy.arange",
"pandas.TimedeltaIndex",
"pandas.Int64Index",
"pandas._testing.index_subclass_makers_generator",
"pandas.DatetimeIndex",
"pandas.infer_freq",
"pandas._testing.makeIntIndex",
"numpy.random.permutation",
"numpy.random.randn",
"pandas.util._test_decorators.async_mark",
"pandas._testing.assert_index_equal",
"numpy.iinfo",
"numpy.array",
"pandas.Interval"
]
] |
KH-Kyle/rmp_nav | [
"d598fe70664a4cdc0e9b9dd4b52e84aa3de1b551"
] | [
"topological_nav/tools/build_nav_graph.py"
] | [
"import numpy as np\nimport cv2\nimport os\nfrom topological_nav.reachability.planning import NavGraph, update_nav_graph, NavGraphSPTM\nfrom rmp_nav.simulation.gibson_map import MakeGibsonMap\nfrom rmp_nav.common.utils import get_gibson_asset_dir, pprint_dict\n\n\ndef _make_maps(map_names):\n def load_maps(datadir, map_names, **kwargs):\n maps = []\n for name in map_names:\n maps.append(MakeGibsonMap(datadir, name, **kwargs))\n return maps\n map_names = [s.strip() for s in map_names]\n map_param = {}\n return load_maps(get_gibson_asset_dir(), map_names, **map_param)\n\n\nclass DatasetRealTrace(object):\n def __init__(self, data_dir, map_name):\n import glob\n self.data_dir = data_dir\n self.map_name = map_name\n\n dirs = os.listdir(data_dir)\n sample_dict = dict()\n\n for d in dirs:\n if os.path.isdir(os.path.join(data_dir, d)):\n samples = []\n img_files = sorted(glob.glob(os.path.join(data_dir, d, '*.tiff')))\n for fn in img_files:\n basename = os.path.splitext(os.path.basename(fn))[0]\n meta_file = os.path.join(data_dir, d, '%s.yaml' % basename)\n metadata = yaml.load(open(meta_file).read(), yaml.SafeLoader)\n samples.append((fn, metadata))\n sample_dict[(0, d)] = samples\n\n self.sample_dict = sample_dict\n print('number of samples: ', sum([len(_) for _ in self.sample_dict.values()]))\n\n self.traj_ids = list(self.sample_dict.keys())\n\n def locate_traj(self, traj_id):\n raw_samples = self.sample_dict[traj_id]\n samples = []\n for fn, metadata in raw_samples:\n samples.append((metadata['pos'], metadata['heading'], fn))\n\n dtype = np.dtype([\n ('pos', (np.float32, 2)),\n ('heading', np.float32),\n ('filenames', 'U128')\n ])\n return np.array(samples, dtype=dtype)\n\n def locate_traj_map(self, traj_id):\n return map_name\n\n def render_traj(self, traj, **kwargs):\n imgs = []\n for fn in traj['filenames']:\n img = cv2.imread(fn, cv2.IMREAD_COLOR)\n img = (cv2.cvtColor(img, cv2.COLOR_BGR2RGB) / 255).astype(np.float32)\n img = img.transpose((2, 0, 1))\n imgs.append(img)\n return imgs\n\n\nif __name__ == '__main__':\n import gflags\n import sys\n import yaml\n from topological_nav.reachability import model_factory\n from topological_nav.tools import eval_envs\n\n gflags.DEFINE_string('env', '', '')\n gflags.DEFINE_string('graph_config', '', '')\n gflags.DEFINE_string('save_file', '', '')\n gflags.DEFINE_string('device', 'cuda', '')\n\n FLAGS = gflags.FLAGS\n FLAGS(sys.argv)\n\n graph_config = yaml.load(open(FLAGS.graph_config).read(), Loader=yaml.SafeLoader)\n print('graph_config:\\n%s' % pprint_dict(graph_config))\n\n model = model_factory.get(graph_config['model'])(device=FLAGS.device)\n\n graph_type = graph_config.get('type', 'ours')\n\n if graph_type == 'ours':\n nav_graph = NavGraph(model['sparsifier'], model['motion_policy'], **graph_config['graph_kwargs'])\n elif graph_type == 'SPTM':\n nav_graph = NavGraphSPTM(model['sparsifier'], model['motion_policy'], **graph_config['graph_kwargs'])\n else:\n raise RuntimeError('Unknown graph type: %s' % graph_type)\n\n data_source = graph_config.get('data_source', 'gibson')\n\n if data_source == 'gibson':\n dataset = eval_envs.make(FLAGS.env, model['sparsifier'])\n map_name = dataset.map_names[0]\n map = _make_maps([map_name])[0]\n dataset._init_once(0)\n dataset.agent.set_map(map)\n\n elif data_source == 'real':\n map_name = graph_config['map']\n map = _make_maps([map_name])[0]\n dataset = DatasetRealTrace(data_dir=graph_config['data_dir'], map_name=map_name)\n\n else:\n raise RuntimeError('Unknown data source %s' % data_source)\n\n traj_ids = sorted(dataset.traj_ids, key=lambda _: _[1])\n # You can either specify traj_idxs or traj_ids in the config YAML.\n filtered_traj_ids = set(graph_config.get('traj_ids', []))\n if filtered_traj_ids:\n traj_ids_to_add = []\n for _ in traj_ids:\n if _[1] in filtered_traj_ids:\n traj_ids_to_add.append(_)\n else:\n traj_idxs = graph_config.get('traj_idxs', list(range(len(traj_ids))))\n traj_ids_to_add = [traj_ids[_] for _ in traj_idxs]\n\n try:\n nav_graph.load(FLAGS.save_file)\n print('loaded', FLAGS.save_file)\n print(nav_graph.extra['id_mapping'])\n except FileNotFoundError:\n os.makedirs(os.path.dirname(FLAGS.save_file), exist_ok=True)\n pass\n\n traj_info_dict = {}\n update_nav_graph(nav_graph, dataset, traj_ids_to_add, traj_info_dict,\n **graph_config.get('builder_kwargs', {}))\n\n print('number of trajs: %d' % len(nav_graph.trajs))\n print('number of traj images: %d' % sum([len(_['samples']) for _ in traj_info_dict.values()]))\n print('number of nodes: %d' % len(nav_graph.graph.nodes))\n print('number of edges: %d' % len(nav_graph.graph.edges))\n print('number of anchors: %d' % sum([len(_) for _ in nav_graph.trajs.values()]))\n\n print('save graph to %s' % FLAGS.save_file)\n nav_graph.extra['model'] = graph_config['model']\n nav_graph.extra['env'] = FLAGS.env\n nav_graph.extra['traj_info'] = traj_info_dict # Useful for visualization, etc.\n\n nav_graph.save(FLAGS.save_file)\n nav_graph.visualize(map, traj_info_dict,\n save_file=os.path.dirname(FLAGS.save_file) + '/graph.svg')\n"
] | [
[
"numpy.array",
"numpy.dtype"
]
] |
ZLLentz/ophyd | [
"c3ae3dac6f37a9befeed0ce80a7684dd645f4bbc"
] | [
"ophyd/tests/test_sim.py"
] | [
"from ophyd.sim import (SynGauss, Syn2DGauss, SynAxis, make_fake_device,\n FakeEpicsSignal, FakeEpicsSignalRO,\n FakeEpicsSignalWithRBV, clear_fake_device,\n instantiate_fake_device, SynSignalWithRegistry)\nfrom ophyd.device import (Device, Component as Cpt, FormattedComponent as FCpt,\n DynamicDeviceComponent as DDCpt)\nfrom ophyd.signal import Signal, EpicsSignal, EpicsSignalRO\nfrom ophyd.areadetector.base import EpicsSignalWithRBV\nfrom ophyd.utils import ReadOnlyError, LimitError, DisconnectedError\nimport numpy as np\nimport pytest\nimport tempfile\nimport shutil\n\n\ndef test_random_state_gauss1d():\n \"\"\"With given random state, the output value should stay the same.\n Test performs on 1D gaussian.\n \"\"\"\n dlist = []\n motor = SynAxis(name='motor')\n for i in range(2):\n s = np.random.RandomState(0)\n noisy_det = SynGauss('noisy_det', motor, 'motor', center=0, Imax=1,\n noise='uniform', sigma=1, noise_multiplier=0.1,\n random_state=s)\n noisy_det.trigger()\n d = noisy_det.read()['noisy_det']['value']\n dlist.append(d)\n assert dlist[0] == dlist[1]\n\n # Without random state, output will be different.\n dlist.clear()\n for i in range(2):\n noisy_det = SynGauss('noisy_det', motor, 'motor', center=0, Imax=1,\n noise='uniform', sigma=1, noise_multiplier=0.1)\n noisy_det.trigger()\n d = noisy_det.read()['noisy_det']['value']\n dlist.append(d)\n assert dlist[0] != dlist[1]\n\n\ndef test_random_state_gauss2d():\n \"\"\"With given random state, the output value should stay the same.\n Test performs on 2D gaussian.\n \"\"\"\n dlist = []\n motor1 = SynAxis(name='motor1')\n motor2 = SynAxis(name='motor2')\n for i in range(2):\n s = np.random.RandomState(0)\n noisy_det = Syn2DGauss('noisy_det', motor1, 'motor1', motor2, 'motor2',\n center=(0, 0), Imax=1, noise='uniform',\n sigma=1, noise_multiplier=0.1, random_state=s)\n noisy_det.trigger()\n d = noisy_det.read()['noisy_det']['value']\n dlist.append(d)\n assert dlist[0] == dlist[1]\n\n\ndef test_synaxis_subcribe():\n hits = dict.fromkeys(['r', 's', 'a'], 0)\n vals = dict.fromkeys(['r', 's', 'a'], None)\n\n def p1(tar, value):\n hits[tar] += 1\n vals[tar] = value\n\n motor = SynAxis(name='motor1')\n # prime the cb cache so these run an subscription\n motor.set(0)\n motor.subscribe(lambda *, value, _tar='a', **kwargs:\n p1(_tar, value))\n motor.readback.subscribe(lambda *, value, _tar='r', **kwargs:\n p1(_tar, value))\n motor.setpoint.subscribe(lambda *, value, _tar='s', **kwargs:\n p1(_tar, value))\n\n assert vals['r'] == motor.readback.get()\n assert vals['a'] == motor.readback.get()\n assert vals['s'] == motor.setpoint.get()\n\n assert all(v == 1 for v in hits.values())\n\n motor.set(1)\n\n assert vals['r'] == motor.readback.get()\n assert vals['a'] == motor.readback.get()\n assert vals['s'] == motor.setpoint.get()\n\n assert all(v == 2 for v in hits.values())\n\n\ndef test_synaxis_timestamps():\n from ophyd.status import wait\n import time\n\n def time_getter(m):\n return {k: v['timestamp']\n for k, v in m.read().items()}\n\n def tester(m, orig_time):\n new_time = time_getter(m)\n assert orig_time != new_time\n return new_time\n\n motor = SynAxis(name='motor1')\n motor.delay = .01\n orig_time = time_getter(motor)\n\n wait(motor.set(3))\n orig_time = tester(motor, orig_time)\n\n wait(motor.setpoint.set(4))\n orig_time = tester(motor, orig_time)\n\n motor.setpoint.put(3)\n time.sleep(2 * motor.delay)\n orig_time = tester(motor, orig_time)\n\n\n# Classes for testing make_fake_device\nclass SampleNested(Device):\n yolk = Cpt(EpicsSignal, ':YOLK', string=True)\n whites = Cpt(EpicsSignalRO, ':WHITES')\n\n\nclass Sample(Device):\n egg = Cpt(SampleNested, ':EGG')\n butter = Cpt(EpicsSignal, ':BUTTER')\n flour = Cpt(EpicsSignalRO, ':FLOUR')\n baster = FCpt(EpicsSignal, '{self.drawer}:BASTER')\n sink = FCpt(EpicsSignal, '{self.sink_location}:SINK')\n fridge = DDCpt({'milk': (EpicsSignal, ':MILK', {}),\n 'cheese': (EpicsSignalRO, ':CHEESE', {})})\n nothing = Cpt(Signal)\n\n def __init__(self, prefix, *, drawer='UNDER_THE_SINK',\n sink_location='COUNTER', **kwargs):\n self.drawer = drawer\n self.sink_location = sink_location\n super().__init__(prefix, **kwargs)\n\n\ndef test_make_fake_device():\n assert make_fake_device(EpicsSignal) == FakeEpicsSignal\n assert make_fake_device(EpicsSignalRO) == FakeEpicsSignalRO\n assert make_fake_device(EpicsSignalWithRBV) == FakeEpicsSignalWithRBV\n\n FakeSample = make_fake_device(Sample)\n my_fake = FakeSample('KITCHEN', name='kitchen')\n assert isinstance(my_fake, Sample)\n\n # Skipped\n assert my_fake.nothing.__class__ is Signal\n\n # Normal\n assert isinstance(my_fake.butter, FakeEpicsSignal)\n assert isinstance(my_fake.flour, FakeEpicsSignalRO)\n assert isinstance(my_fake.sink, FakeEpicsSignal)\n\n # Nested\n assert isinstance(my_fake.egg.yolk, FakeEpicsSignal)\n assert isinstance(my_fake.egg.whites, FakeEpicsSignalRO)\n\n # Dynamic\n assert isinstance(my_fake.fridge.milk, FakeEpicsSignal)\n assert isinstance(my_fake.fridge.cheese, FakeEpicsSignalRO)\n\n my_fake.read()\n\n\ndef test_clear_fake_device():\n FakeSample = make_fake_device(Sample)\n my_fake = FakeSample('KITCHEN', name='kitchen')\n clear_fake_device(my_fake, default_value=49,\n default_string_value='string')\n assert my_fake.butter.get() == 49\n assert my_fake.flour.get() == 49\n assert my_fake.sink.get() == 49\n assert my_fake.egg.yolk.get() == 'string'\n assert my_fake.egg.whites.get() == 49\n\n\ndef test_instantiate_fake_device():\n my_fake = instantiate_fake_device(Sample)\n assert my_fake.drawer == 'UNDER_THE_SINK'\n assert my_fake.sink_location == 'COUNTER'\n assert my_fake.name == 'FakeSample'\n assert my_fake.prefix == '_prefix'\n\n my_fake = instantiate_fake_device(Sample, drawer='JUNK_DRAWER')\n assert my_fake.drawer == 'JUNK_DRAWER'\n assert my_fake.sink_location == 'COUNTER'\n assert my_fake.name == 'FakeSample'\n\n\ndef test_do_not_break_real_class():\n make_fake_device(Sample)\n assert Sample.butter.cls is EpicsSignal\n assert Sample.egg.cls is SampleNested\n assert SampleNested.whites.cls is EpicsSignalRO\n assert Sample.fridge.defn['milk'][0] is EpicsSignal\n\n with pytest.raises(DisconnectedError):\n my_real = Sample('KITCHEN', name='kitchen')\n my_real.read()\n\n\ndef test_fake_epics_signal():\n sig = FakeEpicsSignal('PVNAME', name='sig', limits=True)\n with pytest.raises(ValueError):\n sig.put(None)\n sig.sim_set_limits((0, 10))\n with pytest.raises(LimitError):\n sig.put(11)\n sig.put(4)\n assert sig.get() == 4\n sig.sim_put(5)\n assert sig.get() == 5\n sig.sim_set_putter(lambda x: sig.sim_put(x + 1))\n sig.put(6)\n assert sig.get() == 7\n assert sig.get(as_string=True) == str(7)\n\n\ndef test_fake_epics_signal_ro():\n sig = FakeEpicsSignalRO('PVNAME', name='sig')\n with pytest.raises(ReadOnlyError):\n sig.put(3)\n with pytest.raises(ReadOnlyError):\n sig.put(4)\n with pytest.raises(ReadOnlyError):\n sig.set(5)\n sig.sim_put(1)\n assert sig.get() == 1\n\n\ndef test_fake_epics_signal_enum():\n sig = FakeEpicsSignal('PVNAME', name='sig', string=True)\n sig.sim_set_enum_strs(['zero', 'one', 'two', 'three'])\n sig.put(0)\n assert sig.describe()['sig']['enum_strs'] == ('zero', 'one', 'two', 'three')\n assert sig.get() == 'zero'\n assert sig.get(as_string=False) == 0\n sig.put('two')\n assert sig.get(as_string=False) == 2\n with pytest.raises(ValueError):\n sig.put('bazillion')\n\n\ndef test_SynSignalWithRegistry():\n tempdirname = tempfile.mkdtemp()\n\n def data_func():\n return np.array(np.ones((10, 10)))\n\n img = SynSignalWithRegistry(data_func, save_path=tempdirname,\n name='img', labels={'detectors'})\n img.stage()\n img.trigger()\n d0 = img.read()\n assert int(d0['img']['value'][-1]) == 0\n img.trigger()\n d1 = img.read()\n assert int(d1['img']['value'][-1]) == 1 # increased by 1\n shutil.rmtree(tempdirname)\n\n\ndef test_synaxis_describe():\n bs = pytest.importorskip('bluesky')\n import bluesky.plans as bp\n motor1 = SynAxis(name='motor1')\n RE = bs.RunEngine()\n RE(bp.scan([], motor1, -5, 5, 5))\n\n\ndef test_describe(hw):\n # These need to be staged and triggered before they can be described, just\n # like real area detectors do. We plan to change this approach and remove\n # this limitation in ophyd 1.6.0, but for now we'll just skip these.\n SKIP = (\n 'img',\n 'direct_img',\n 'direct_img_list',\n )\n for name, obj in hw.__dict__.items():\n if name in SKIP:\n continue\n if hasattr(obj, 'describe'):\n obj.describe()\n elif hasattr(obj, 'describe_collect'):\n obj.describe_collect()\n else:\n raise AttributeError(\"expected describe or describe_collect\")\n"
] | [
[
"numpy.random.RandomState",
"numpy.ones"
]
] |
JSchapke/bazzan_environment | [
"38c7bba4be47c855f1844758c03a299d5ec94649"
] | [
"ga.py"
] | [
"import os\nimport argparse\nimport datetime\nimport random\nfrom functools import partial\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom lib.pyeasyga import GeneticAlgorithm\nfrom env import Env\n\ndef create_individual(action_space, *args):\n high = action_space.high\n low = action_space.low\n return [random.randint(low[i], high[i]) for i in range(len(high))]\n\ndef fitness(env, actions, *args):\n rewards = env.step(actions)\n return np.mean(rewards)\n\ndef mutate(action_space, individual):\n high = action_space.high\n low = action_space.low\n index = random.randrange(len(individual))\n individual[index] = random.randint(low[index], high[index])\n\ndef build_ga(env, \n population, \n crossover_rate=0,\n mutation_rate=0,\n generations=1,\n elitism=0,\n **kwargs):\n _fitness = partial(fitness, env)\n _mutate = partial(mutate, env.action_space)\n _create_individual = partial(create_individual, env.action_space)\n\n ga = GeneticAlgorithm(None,\n population_size=population,\n generations=generations,\n crossover_probability=crossover_rate,\n mutation_probability=mutation_rate,\n elitism=elitism,\n maximise_fitness=True )\n ga.create_individual = _create_individual\n ga.mutate_function = _mutate\n ga.fitness_function = _fitness\n return ga\n\n\ndef run_ga(env, n_runs, env_steps, ga_params):\n rewards = np.zeros((n_runs, env_steps))\n pop = ga_params['population']\n\n for r in range(n_runs):\n ga = build_ga(env, **ga_params)\n ga.create_first_generation()\n cur_step = pop\n\n for s in range(env_steps):\n if cur_step == s:\n ga.create_next_generation()\n cur_step += pop\n\n reward = ga.best_individual()[0]\n rewards[r, s] = reward\n\n print(f'Run {r+1}/{n_runs} - Step {s+1}/{env_steps} - Generation Reward: {reward}', end='\\r')\n return rewards\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n # Environment Params\n parser.add_argument('netfile')\n parser.add_argument('--s', help='Max number of steps allowed from an origin to a destination node.', default=2, type=int)\n parser.add_argument('--k', help='Max number of shortest paths from an origin to a destination node.', default=2, type=int)\n # Agent Params\n parser.add_argument('--generations', '-g', help='Number of generations to run.', default=500, type=int)\n parser.add_argument('--population', '-p', help='Size of population.', default=20, type=int)\n parser.add_argument('--crossover_rate', '-c', help='Rate of crossover.', default=0.5, type=float)\n parser.add_argument('--mutation_rate', '-m', help='Rate of mutation.', default=0.5, type=float)\n parser.add_argument('--elitism', '-e', help='Size of the elite.', default=0)\n # Simulation Params\n parser.add_argument('--env_steps', help='Number of environment steps to run.', default=1000, type=int)\n parser.add_argument('--runs', help='Number of runs for GA.', default=1, type=int)\n parser.add_argument('--outdir', help='Output dir for the plot.', default='./figs/')\n return parser.parse_args()\n\nif __name__ == '__main__':\n print('- Starting Generic Algorithm -')\n args = parse_args()\n\n now = datetime.datetime.now()\n hour = ('0' + str(now.hour))[-2:]\n minute = ('0' + str(now.minute))[-2:]\n filename = f'GA_g{args.generations}_p{args.population}_{hour}{minute}.png'\n outpath = os.path.join(args.outdir, filename)\n if not os.path.isdir(args.outdir):\n os.makedirs(args.outdir)\n\n hists = []\n env = Env(args.netfile, h=args.s, k=args.k)\n action_space = env.action_space\n\n\n ga_params = dict(\n population=args.population, \n crossover_rate=args.crossover_rate,\n mutation_rate=args.mutation_rate,\n elitism=args.elitism)\n\n rewards = run_ga(env, args.runs, args.env_steps, ga_params)\n\n generations = range(args.generations)\n means = rewards.mean(0)\n stds = rewards.std(0)\n\n fig, ax = plt.subplots(figsize=(8, 6))\n ax.set_title('Genetic Algorithm rewards')\n ax.set_xlabel('Generation')\n ax.set_ylabel('Reward')\n ax.plot(generations, means, label='AVG. Generation Reward')\n plt.fill_between(generations, means-stds, means+stds,alpha=0.2)\n legend = ax.legend(loc='lower right', shadow=True)\n plt.savefig(outpath)\n print(f'Figure saved to: {outpath}')\n\n"
] | [
[
"numpy.zeros",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.fill_between",
"numpy.mean"
]
] |
julramos/sktime | [
"192b5ec5e6e4e4ee2e956b48e1cd5930aa193a84"
] | [
"sktime/tests/_config.py"
] | [
"#!/usr/bin/env python3 -u\n# -*- coding: utf-8 -*-\n# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)\n\n__author__ = [\"Markus Löning\"]\n__all__ = [\"ESTIMATOR_TEST_PARAMS\", \"EXCLUDE_ESTIMATORS\", \"EXCLUDED_TESTS\"]\n\nimport numpy as np\n\nfrom hcrystalball.wrappers import HoltSmoothingWrapper\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import FunctionTransformer\nfrom sklearn.preprocessing import StandardScaler\nfrom sktime.forecasting.fbprophet import Prophet\nfrom sktime.base import BaseEstimator\nfrom sktime.classification.base import BaseClassifier\nfrom sktime.classification.compose import ColumnEnsembleClassifier\nfrom sktime.classification.compose import ComposableTimeSeriesForestClassifier\nfrom sktime.classification.dictionary_based import ContractableBOSS\nfrom sktime.classification.dictionary_based import TemporalDictionaryEnsemble\nfrom sktime.classification.interval_based import RandomIntervalSpectralForest\nfrom sktime.classification.interval_based._cif import CanonicalIntervalForest\nfrom sktime.classification.interval_based._drcif import DrCIF\nfrom sktime.classification.interval_based import TimeSeriesForestClassifier as TSFC\nfrom sktime.classification.interval_based import SupervisedTimeSeriesForest\nfrom sktime.classification.shapelet_based import ROCKETClassifier\nfrom sktime.classification.shapelet_based import ShapeletTransformClassifier\nfrom sktime.forecasting.arima import AutoARIMA\nfrom sktime.forecasting.base import BaseForecaster\nfrom sktime.forecasting.bats import BATS\nfrom sktime.forecasting.compose import DirectTabularRegressionForecaster\nfrom sktime.forecasting.compose import DirRecTimeSeriesRegressionForecaster\nfrom sktime.forecasting.compose import DirectTimeSeriesRegressionForecaster\nfrom sktime.forecasting.compose import DirRecTabularRegressionForecaster\nfrom sktime.forecasting.compose import EnsembleForecaster\nfrom sktime.forecasting.compose import MultioutputTabularRegressionForecaster\nfrom sktime.forecasting.compose import MultioutputTimeSeriesRegressionForecaster\nfrom sktime.forecasting.compose import RecursiveTabularRegressionForecaster\nfrom sktime.forecasting.compose import RecursiveTimeSeriesRegressionForecaster\nfrom sktime.forecasting.compose import StackingForecaster\nfrom sktime.forecasting.compose import TransformedTargetForecaster\nfrom sktime.forecasting.compose import MultiplexForecaster\nfrom sktime.forecasting.exp_smoothing import ExponentialSmoothing\nfrom sktime.forecasting.hcrystalball import HCrystalBallForecaster\nfrom sktime.forecasting.model_selection import ForecastingGridSearchCV\nfrom sktime.forecasting.model_selection import ForecastingRandomizedSearchCV\nfrom sktime.forecasting.model_selection import SingleWindowSplitter\nfrom sktime.forecasting.naive import NaiveForecaster\nfrom sktime.forecasting.online_learning import OnlineEnsembleForecaster\nfrom sktime.forecasting.tbats import TBATS\nfrom sktime.forecasting.theta import ThetaForecaster\nfrom sktime.performance_metrics.forecasting import MeanAbsolutePercentageError\nfrom sktime.regression.base import BaseRegressor\nfrom sktime.regression.compose import ComposableTimeSeriesForestRegressor\nfrom sktime.series_as_features.compose import FeatureUnion\nfrom sktime.transformations.base import BaseTransformer\nfrom sktime.transformations.base import _PanelToPanelTransformer\nfrom sktime.transformations.base import _PanelToTabularTransformer\nfrom sktime.transformations.base import _SeriesToPrimitivesTransformer\nfrom sktime.transformations.base import _SeriesToSeriesTransformer\nfrom sktime.transformations.panel.compose import ColumnTransformer\nfrom sktime.transformations.panel.compose import (\n SeriesToPrimitivesRowTransformer,\n)\nfrom sktime.transformations.panel.compose import SeriesToSeriesRowTransformer\nfrom sktime.transformations.panel.dictionary_based import SFA\nfrom sktime.transformations.panel.interpolate import TSInterpolator\nfrom sktime.transformations.panel.reduce import Tabularizer\nfrom sktime.transformations.panel.shapelets import ContractedShapeletTransform\nfrom sktime.transformations.panel.shapelets import ShapeletTransform\nfrom sktime.transformations.panel.summarize import FittedParamExtractor\nfrom sktime.transformations.panel.tsfresh import TSFreshFeatureExtractor\nfrom sktime.transformations.panel.tsfresh import (\n TSFreshRelevantFeatureExtractor,\n)\nfrom sktime.transformations.series.acf import AutoCorrelationTransformer\nfrom sktime.transformations.series.acf import PartialAutoCorrelationTransformer\nfrom sktime.transformations.series.adapt import TabularToSeriesAdaptor\nfrom sktime.transformations.series.detrend import Detrender\nfrom sktime.transformations.series.impute import Imputer\nfrom sktime.transformations.series.compose import OptionalPassthrough\nfrom sktime.transformations.series.outlier_detection import HampelFilter\nfrom sktime.transformations.series.boxcox import BoxCoxTransformer\n\n\n# The following estimators currently do not pass all unit tests\n# What do they fail? ShapeDTW fails on 3d_numpy_input test, not set up for that\nEXCLUDE_ESTIMATORS = [\n \"ShapeDTW\",\n \"HIVECOTEV1\",\n \"ElasticEnsemble\",\n \"ProximityForest\",\n \"ProximityStump\",\n \"ProximityTree\",\n]\n\nEXCLUDED_TESTS = {\n \"ShapeletTransformClassifier\": [\"check_fit_idempotent\"],\n \"ContractedShapeletTransform\": [\"check_fit_idempotent\"],\n}\n\n# We here configure estimators for basic unit testing, including setting of\n# required hyper-parameters and setting of hyper-parameters for faster training.\nSERIES_TO_SERIES_TRANSFORMER = StandardScaler()\nSERIES_TO_PRIMITIVES_TRANSFORMER = FunctionTransformer(\n np.mean, kw_args={\"axis\": 0}, check_inverse=False\n)\nTRANSFORMERS = [\n (\n \"transformer1\",\n SeriesToSeriesRowTransformer(\n SERIES_TO_SERIES_TRANSFORMER, check_transformer=False\n ),\n ),\n (\n \"transformer2\",\n SeriesToSeriesRowTransformer(\n SERIES_TO_SERIES_TRANSFORMER, check_transformer=False\n ),\n ),\n]\nREGRESSOR = LinearRegression()\nTIME_SERIES_CLASSIFIER = TSFC(n_estimators=3)\nTIME_SERIES_CLASSIFIERS = [\n (\"tsf1\", TIME_SERIES_CLASSIFIER),\n (\"tsf2\", TIME_SERIES_CLASSIFIER),\n]\nFORECASTER = ExponentialSmoothing()\nFORECASTERS = [(\"ses1\", FORECASTER), (\"ses2\", FORECASTER)]\nSTEPS = [\n (\"transformer\", Detrender(ThetaForecaster())),\n (\"forecaster\", NaiveForecaster()),\n]\nESTIMATOR_TEST_PARAMS = {\n OnlineEnsembleForecaster: {\"forecasters\": FORECASTERS},\n FeatureUnion: {\"transformer_list\": TRANSFORMERS},\n DirectTabularRegressionForecaster: {\"estimator\": REGRESSOR},\n MultioutputTabularRegressionForecaster: {\"estimator\": REGRESSOR},\n RecursiveTabularRegressionForecaster: {\"estimator\": REGRESSOR},\n DirRecTabularRegressionForecaster: {\"estimator\": REGRESSOR},\n DirectTimeSeriesRegressionForecaster: {\n \"estimator\": make_pipeline(Tabularizer(), REGRESSOR)\n },\n RecursiveTimeSeriesRegressionForecaster: {\n \"estimator\": make_pipeline(Tabularizer(), REGRESSOR)\n },\n MultioutputTimeSeriesRegressionForecaster: {\n \"estimator\": make_pipeline(Tabularizer(), REGRESSOR)\n },\n DirRecTimeSeriesRegressionForecaster: {\n \"estimator\": make_pipeline(Tabularizer(), REGRESSOR)\n },\n TransformedTargetForecaster: {\"steps\": STEPS},\n EnsembleForecaster: {\"forecasters\": FORECASTERS},\n StackingForecaster: {\"forecasters\": FORECASTERS, \"final_regressor\": REGRESSOR},\n Detrender: {\"forecaster\": FORECASTER},\n ForecastingGridSearchCV: {\n \"forecaster\": NaiveForecaster(strategy=\"mean\"),\n \"cv\": SingleWindowSplitter(fh=1),\n \"param_grid\": {\"window_length\": [2, 5]},\n \"scoring\": MeanAbsolutePercentageError(symmetric=True),\n },\n ForecastingRandomizedSearchCV: {\n \"forecaster\": NaiveForecaster(strategy=\"mean\"),\n \"cv\": SingleWindowSplitter(fh=1),\n \"param_distributions\": {\"window_length\": [2, 5]},\n \"scoring\": MeanAbsolutePercentageError(symmetric=True),\n },\n TabularToSeriesAdaptor: {\"transformer\": StandardScaler()},\n ColumnEnsembleClassifier: {\n \"estimators\": [\n (name, estimator, 0) for (name, estimator) in TIME_SERIES_CLASSIFIERS\n ]\n },\n FittedParamExtractor: {\n \"forecaster\": FORECASTER,\n \"param_names\": [\"initial_level\"],\n },\n SeriesToPrimitivesRowTransformer: {\n \"transformer\": SERIES_TO_PRIMITIVES_TRANSFORMER,\n \"check_transformer\": False,\n },\n SeriesToSeriesRowTransformer: {\n \"transformer\": SERIES_TO_SERIES_TRANSFORMER,\n \"check_transformer\": False,\n },\n ColumnTransformer: {\n \"transformers\": [(name, estimator, [0]) for name, estimator in TRANSFORMERS]\n },\n AutoARIMA: {\n \"d\": 0,\n \"suppress_warnings\": True,\n \"max_p\": 2,\n \"max_q\": 2,\n \"seasonal\": False,\n },\n MultiplexForecaster: {\n \"forecasters\": [\n (\"Naive_mean\", NaiveForecaster(strategy=\"mean\")),\n (\"Naive_last\", NaiveForecaster(strategy=\"last\")),\n (\"Naive_drift\", NaiveForecaster(strategy=\"drift\")),\n ],\n \"selected_forecaster\": \"Naive_mean\",\n },\n ShapeletTransformClassifier: {\"n_estimators\": 3, \"time_contract_in_mins\": 0.125},\n ContractedShapeletTransform: {\"time_contract_in_mins\": 0.125},\n ShapeletTransform: {\n \"max_shapelets_to_store_per_class\": 1,\n \"min_shapelet_length\": 3,\n \"max_shapelet_length\": 4,\n },\n ROCKETClassifier: {\"num_kernels\": 100},\n TSFreshFeatureExtractor: {\"disable_progressbar\": True, \"show_warnings\": False},\n TSFreshRelevantFeatureExtractor: {\n \"disable_progressbar\": True,\n \"show_warnings\": False,\n \"fdr_level\": 0.01,\n },\n TSInterpolator: {\"length\": 10},\n RandomIntervalSpectralForest: {\"n_estimators\": 3, \"acf_lag\": 10, \"min_interval\": 5},\n SFA: {\"return_pandas_data_series\": True},\n ContractableBOSS: {\"n_parameter_samples\": 25, \"max_ensemble_size\": 5},\n TemporalDictionaryEnsemble: {\n \"n_parameter_samples\": 25,\n \"max_ensemble_size\": 5,\n \"randomly_selected_params\": 20,\n },\n TSFC: {\"n_estimators\": 3},\n ComposableTimeSeriesForestClassifier: {\"n_estimators\": 3},\n ComposableTimeSeriesForestRegressor: {\"n_estimators\": 3},\n SupervisedTimeSeriesForest: {\"n_estimators\": 3},\n CanonicalIntervalForest: {\"n_estimators\": 3},\n DrCIF: {\"n_estimators\": 3},\n HCrystalBallForecaster: {\"model\": HoltSmoothingWrapper()},\n BATS: {\n \"use_box_cox\": False,\n \"use_trend\": False,\n \"use_damped_trend\": False,\n \"sp\": [],\n \"use_arma_errors\": False,\n \"n_jobs\": 1,\n },\n TBATS: {\n \"use_box_cox\": False,\n \"use_trend\": False,\n \"use_damped_trend\": False,\n \"sp\": [],\n \"use_arma_errors\": False,\n \"n_jobs\": 1,\n },\n Prophet: {\n \"n_changepoints\": 0,\n \"yearly_seasonality\": False,\n \"weekly_seasonality\": False,\n \"daily_seasonality\": False,\n \"uncertainty_samples\": 1000,\n \"verbose\": False,\n },\n PartialAutoCorrelationTransformer: {\"n_lags\": 1},\n AutoCorrelationTransformer: {\"n_lags\": 1},\n Imputer: {\"method\": \"mean\"},\n HampelFilter: {\"window_length\": 3},\n OptionalPassthrough: {\"transformer\": BoxCoxTransformer(), \"passthrough\": True},\n}\n\n# We use estimator tags in addition to class hierarchies to further distinguish\n# estimators into different categories. This is useful for defining and running\n# common tests for estimators with the same tags.\nVALID_ESTIMATOR_TAGS = (\n \"fit-in-transform\", # fitted in transform or non-fittable\n \"univariate-only\",\n \"transform-returns-same-time-index\",\n \"handles-missing-data\",\n \"skip-inverse-transform\",\n)\n\n# These methods should not change the state of the estimator, that is, they should\n# not change fitted parameters or hyper-parameters. They are also the methods that\n# \"apply\" the fitted estimator to data and useful for checking results.\nNON_STATE_CHANGING_METHODS = (\n \"predict\",\n \"predict_proba\",\n \"decision_function\",\n \"transform\",\n \"inverse_transform\",\n)\n\n# The following gives a list of valid estimator base classes.\nVALID_TRANSFORMER_TYPES = (\n _SeriesToPrimitivesTransformer,\n _SeriesToSeriesTransformer,\n _PanelToTabularTransformer,\n _PanelToPanelTransformer,\n)\nVALID_ESTIMATOR_BASE_TYPES = (\n BaseClassifier,\n BaseRegressor,\n BaseForecaster,\n BaseTransformer,\n)\nVALID_ESTIMATOR_TYPES = (\n BaseEstimator,\n *VALID_ESTIMATOR_BASE_TYPES,\n *VALID_TRANSFORMER_TYPES,\n)\n\nVALID_ESTIMATOR_BASE_TYPE_LOOKUP = {\n \"classifier\": BaseClassifier,\n \"regressor\": BaseRegressor,\n \"forecaster\": BaseForecaster,\n \"transformer\": BaseTransformer,\n}\n"
] | [
[
"sklearn.preprocessing.StandardScaler",
"sklearn.linear_model.LinearRegression",
"sklearn.preprocessing.FunctionTransformer"
]
] |
Jerrypiglet/Total3DUnderstanding | [
"655d00a988c839af3b73f8ab890c3f70c1500147"
] | [
"models/mgnet/modules/network.py"
] | [
"# Mesh Generation Net: model loader\n# author: ynie\n# date: Feb, 2020\n\nfrom models.registers import METHODS, MODULES, LOSSES\nfrom models.network import BaseNetwork\nimport torch\nfrom torch import nn\n\[email protected]_module\nclass MGNet(BaseNetwork):\n\n def __init__(self, cfg):\n '''\n load submodules for the network.\n :param config: customized configurations.\n '''\n super(BaseNetwork, self).__init__()\n self.cfg = cfg\n\n '''load network blocks'''\n for phase_name, net_spec in cfg.config['model'].items():\n method_name = net_spec['method']\n # load specific optimizer parameters\n optim_spec = self.load_optim_spec(cfg.config, net_spec)\n subnet = MODULES.get(method_name)(cfg, optim_spec)\n self.add_module(phase_name, subnet)\n\n '''load corresponding loss functions'''\n setattr(self, phase_name + '_loss', LOSSES.get(self.cfg.config['model'][phase_name]['loss'], 'Null')(\n self.cfg.config['model'][phase_name].get('weight', 1)))\n\n '''Multi-GPU setting'''\n self.mesh_reconstruction = nn.DataParallel(self.mesh_reconstruction)\n\n '''freeze submodules or not'''\n self.freeze_modules(cfg)\n\n def forward(self, data):\n\n mesh_coordinates_results, points_from_edges, point_indicators, output_edges, boundary_point_ids, faces = self.mesh_reconstruction(\n data['img'], data['cls'], threshold=0.2, factor=1)\n\n return {'mesh_coordinates_results':mesh_coordinates_results, 'points_from_edges':points_from_edges,\n 'point_indicators':point_indicators, 'output_edges':output_edges, 'boundary_point_ids':boundary_point_ids, 'faces':faces}\n\n def loss(self, est_data, gt_data):\n '''\n calculate loss of est_out given gt_out.\n '''\n loss = self.mesh_reconstruction_loss(est_data, gt_data, self.cfg.config['data']['tmn_subnetworks'],\n self.cfg.config['data']['face_samples'])\n total_loss = sum(loss.values())\n for key, item in loss.items():\n loss[key] = item.item()\n return {'total':total_loss, **loss}"
] | [
[
"torch.nn.DataParallel"
]
] |
loopylangur/allennlp | [
"0fc695b08a0376317e45ae0a45584aa9eb14beb6"
] | [
"allennlp/training/trainer.py"
] | [
"import datetime\nimport logging\nimport math\nimport os\nimport time\nimport traceback\nfrom typing import Dict, Optional, Tuple, Union, Iterable, Any\n\nimport torch\nimport torch.distributed as dist\nimport torch.optim.lr_scheduler\nfrom torch.nn.parallel import DistributedDataParallel\n\nfrom allennlp.common import Params\nfrom allennlp.common.checks import ConfigurationError, parse_cuda_device, check_for_gpu\nfrom allennlp.common.tqdm import Tqdm\nfrom allennlp.common.util import dump_metrics, gpu_memory_mb, peak_memory_mb, lazy_groups_of\nfrom allennlp.data.instance import Instance\nfrom allennlp.data.iterators.data_iterator import DataIterator, TensorDict\nfrom allennlp.models.model import Model\nfrom allennlp.nn import util as nn_util\nfrom allennlp.training import util as training_util\nfrom allennlp.training.checkpointer import Checkpointer\nfrom allennlp.training.learning_rate_schedulers import LearningRateScheduler\nfrom allennlp.training.metric_tracker import MetricTracker\nfrom allennlp.training.momentum_schedulers import MomentumScheduler\nfrom allennlp.training.moving_average import MovingAverage\nfrom allennlp.training.optimizers import Optimizer\nfrom allennlp.training.tensorboard_writer import TensorboardWriter\nfrom allennlp.training.trainer_base import TrainerBase\n\nlogger = logging.getLogger(__name__)\n\n\[email protected](\"default\")\nclass Trainer(TrainerBase):\n def __init__(\n self,\n model: Model,\n optimizer: torch.optim.Optimizer,\n iterator: DataIterator,\n train_dataset: Iterable[Instance],\n validation_dataset: Optional[Iterable[Instance]] = None,\n patience: Optional[int] = None,\n validation_metric: str = \"-loss\",\n validation_iterator: DataIterator = None,\n shuffle: bool = True,\n num_epochs: int = 20,\n serialization_dir: Optional[str] = None,\n num_serialized_models_to_keep: int = 20,\n keep_serialized_model_every_num_seconds: int = None,\n checkpointer: Checkpointer = None,\n model_save_interval: float = None,\n cuda_device: int = -1,\n grad_norm: Optional[float] = None,\n grad_clipping: Optional[float] = None,\n learning_rate_scheduler: Optional[LearningRateScheduler] = None,\n momentum_scheduler: Optional[MomentumScheduler] = None,\n summary_interval: int = 100,\n histogram_interval: int = None,\n should_log_parameter_statistics: bool = True,\n should_log_learning_rate: bool = False,\n log_batch_size_period: Optional[int] = None,\n moving_average: Optional[MovingAverage] = None,\n distributed: bool = False,\n rank: int = 0,\n world_size: int = 1,\n num_gradient_accumulation_steps: int = 1,\n ) -> None:\n \"\"\"\n A trainer for doing supervised learning. It just takes a labeled dataset\n and a ``DataIterator``, and uses the supplied ``Optimizer`` to learn the weights\n for your model over some fixed number of epochs. You can also pass in a validation\n dataset and enable early stopping. There are many other bells and whistles as well.\n\n # Parameters\n\n model : ``Model``, required.\n An AllenNLP model to be optimized. Pytorch Modules can also be optimized if\n their ``forward`` method returns a dictionary with a \"loss\" key, containing a\n scalar tensor representing the loss function to be optimized.\n\n If you are training your model using GPUs, your model should already be\n on the correct device. (If you use `Trainer.from_params` this will be\n handled for you.)\n optimizer : ``torch.nn.Optimizer``, required.\n An instance of a Pytorch Optimizer, instantiated with the parameters of the\n model to be optimized.\n iterator : ``DataIterator``, required.\n A method for iterating over a ``Dataset``, yielding padded indexed batches.\n train_dataset : ``Dataset``, required.\n A ``Dataset`` to train on. The dataset should have already been indexed.\n validation_dataset : ``Dataset``, optional, (default = None).\n A ``Dataset`` to evaluate on. The dataset should have already been indexed.\n patience : Optional[int] > 0, optional (default=None)\n Number of epochs to be patient before early stopping: the training is stopped\n after ``patience`` epochs with no improvement. If given, it must be ``> 0``.\n If None, early stopping is disabled.\n validation_metric : str, optional (default=\"loss\")\n Validation metric to measure for whether to stop training using patience\n and whether to serialize an ``is_best`` model each epoch. The metric name\n must be prepended with either \"+\" or \"-\", which specifies whether the metric\n is an increasing or decreasing function.\n validation_iterator : ``DataIterator``, optional (default=None)\n An iterator to use for the validation set. If ``None``, then\n use the training `iterator`.\n shuffle : ``bool``, optional (default=True)\n Whether to shuffle the instances in the iterator or not.\n num_epochs : int, optional (default = 20)\n Number of training epochs.\n serialization_dir : str, optional (default=None)\n Path to directory for saving and loading model files. Models will not be saved if\n this parameter is not passed.\n num_serialized_models_to_keep : ``int``, optional (default=20)\n Number of previous model checkpoints to retain. Default is to keep 20 checkpoints.\n A value of None or -1 means all checkpoints will be kept.\n keep_serialized_model_every_num_seconds : ``int``, optional (default=None)\n If num_serialized_models_to_keep is not None, then occasionally it's useful to\n save models at a given interval in addition to the last num_serialized_models_to_keep.\n To do so, specify keep_serialized_model_every_num_seconds as the number of seconds\n between permanently saved checkpoints. Note that this option is only used if\n num_serialized_models_to_keep is not None, otherwise all checkpoints are kept.\n checkpointer : ``Checkpointer``, optional (default=None)\n An instance of class Checkpointer to use instead of the default. If a checkpointer is specified,\n the arguments num_serialized_models_to_keep and keep_serialized_model_every_num_seconds should\n not be specified. The caller is responsible for initializing the checkpointer so that it is\n consistent with serialization_dir.\n model_save_interval : ``float``, optional (default=None)\n If provided, then serialize models every ``model_save_interval``\n seconds within single epochs. In all cases, models are also saved\n at the end of every epoch if ``serialization_dir`` is provided.\n cuda_device : ``int``, optional (default = -1)\n An integer specifying the CUDA device(s) to use for this process. If -1, the CPU is used.\n Data parallelism is controlled at the allennlp train level, so each trainer will have a single\n GPU.\n grad_norm : ``float``, optional, (default = None).\n If provided, gradient norms will be rescaled to have a maximum of this value.\n grad_clipping : ``float``, optional (default = ``None``).\n If provided, gradients will be clipped `during the backward pass` to have an (absolute)\n maximum of this value. If you are getting ``NaNs`` in your gradients during training\n that are not solved by using ``grad_norm``, you may need this.\n learning_rate_scheduler : ``LearningRateScheduler``, optional (default = None)\n If specified, the learning rate will be decayed with respect to\n this schedule at the end of each epoch (or batch, if the scheduler implements\n the ``step_batch`` method). If you use :class:`torch.optim.lr_scheduler.ReduceLROnPlateau`,\n this will use the ``validation_metric`` provided to determine if learning has plateaued.\n To support updating the learning rate on every batch, this can optionally implement\n ``step_batch(batch_num_total)`` which updates the learning rate given the batch number.\n momentum_scheduler : ``MomentumScheduler``, optional (default = None)\n If specified, the momentum will be updated at the end of each batch or epoch\n according to the schedule.\n summary_interval : ``int``, optional, (default = 100)\n Number of batches between logging scalars to tensorboard\n histogram_interval : ``int``, optional, (default = ``None``)\n If not None, then log histograms to tensorboard every ``histogram_interval`` batches.\n When this parameter is specified, the following additional logging is enabled:\n * Histograms of model parameters\n * The ratio of parameter update norm to parameter norm\n * Histogram of layer activations\n We log histograms of the parameters returned by\n ``model.get_parameters_for_histogram_tensorboard_logging``.\n The layer activations are logged for any modules in the ``Model`` that have\n the attribute ``should_log_activations`` set to ``True``. Logging\n histograms requires a number of GPU-CPU copies during training and is typically\n slow, so we recommend logging histograms relatively infrequently.\n Note: only Modules that return tensors, tuples of tensors or dicts\n with tensors as values currently support activation logging.\n should_log_parameter_statistics : ``bool``, optional, (default = True)\n Whether to send parameter statistics (mean and standard deviation\n of parameters and gradients) to tensorboard.\n should_log_learning_rate : ``bool``, optional, (default = False)\n Whether to send parameter specific learning rate to tensorboard.\n log_batch_size_period : ``int``, optional, (default = ``None``)\n If defined, how often to log the average batch size.\n moving_average : ``MovingAverage``, optional, (default = None)\n If provided, we will maintain moving averages for all parameters. During training, we\n employ a shadow variable for each parameter, which maintains the moving average. During\n evaluation, we backup the original parameters and assign the moving averages to corresponding\n parameters. Be careful that when saving the checkpoint, we will save the moving averages of\n parameters. This is necessary because we want the saved model to perform as well as the validated\n model if we load it later. But this may cause problems if you restart the training from checkpoint.\n distributed : ``bool``, optional, (default = False)\n If set, PyTorch's `DistributedDataParallel` is used to train the model in multiple GPUs. This also\n requires `world_size` to be greater than 1.\n rank : ``int``, optional, (default = 0)\n This is the unique identifier of the `Trainer` in a distributed process group. The GPU device id is\n used as the rank.\n world_size : ``int``, (default = 1)\n The number of `Trainer` workers participating in the distributed training.\n num_gradient_accumulation_steps : ``int``, optional, (default = 1)\n Gradients are accumulated for the given number of steps before doing an optimizer step. This can\n be useful to accommodate batches that are larger than the RAM size. Refer Thomas Wolf's\n [post](https://tinyurl.com/y5mv44fw) for details on Gradient Accumulation.\n \"\"\"\n super().__init__(serialization_dir, cuda_device, distributed, rank, world_size)\n\n # I am not calling move_to_gpu here, because if the model is\n # not already on the GPU then the optimizer is going to be wrong.\n self.model = model\n\n self.iterator = iterator\n self._validation_iterator = validation_iterator\n self.shuffle = shuffle\n self.optimizer = optimizer\n self.train_data = train_dataset\n self._validation_data = validation_dataset\n\n if patience is None: # no early stopping\n if validation_dataset:\n logger.warning(\n \"You provided a validation dataset but patience was set to None, \"\n \"meaning that early stopping is disabled\"\n )\n elif (not isinstance(patience, int)) or patience <= 0:\n raise ConfigurationError(\n '{} is an invalid value for \"patience\": it must be a positive integer '\n \"or None (if you want to disable early stopping)\".format(patience)\n )\n\n # For tracking is_best_so_far and should_stop_early\n self._metric_tracker = MetricTracker(patience, validation_metric)\n # Get rid of + or -\n self._validation_metric = validation_metric[1:]\n\n self._num_epochs = num_epochs\n\n if checkpointer is not None:\n # We can't easily check if these parameters were passed in, so check against their default values.\n # We don't check against serialization_dir since it is also used by the parent class.\n if (\n num_serialized_models_to_keep != 20\n or keep_serialized_model_every_num_seconds is not None\n ):\n raise ConfigurationError(\n \"When passing a custom Checkpointer, you may not also pass in separate checkpointer \"\n \"args 'num_serialized_models_to_keep' or 'keep_serialized_model_every_num_seconds'.\"\n )\n self._checkpointer = checkpointer\n else:\n self._checkpointer = Checkpointer(\n serialization_dir,\n keep_serialized_model_every_num_seconds,\n num_serialized_models_to_keep,\n )\n\n self._model_save_interval = model_save_interval\n\n self._grad_norm = grad_norm\n self._grad_clipping = grad_clipping\n\n self._learning_rate_scheduler = learning_rate_scheduler\n self._momentum_scheduler = momentum_scheduler\n self._moving_average = moving_average\n\n # We keep the total batch number as an instance variable because it\n # is used inside a closure for the hook which logs activations in\n # ``_enable_activation_logging``.\n self._batch_num_total = 0\n\n self._tensorboard = TensorboardWriter(\n get_batch_num_total=lambda: self._batch_num_total,\n serialization_dir=serialization_dir,\n summary_interval=summary_interval,\n histogram_interval=histogram_interval,\n should_log_parameter_statistics=should_log_parameter_statistics,\n should_log_learning_rate=should_log_learning_rate,\n )\n\n self._log_batch_size_period = log_batch_size_period\n\n self._last_log = 0.0 # time of last logging\n\n self._num_gradient_accumulation_steps = num_gradient_accumulation_steps\n\n # Enable activation logging.\n if histogram_interval is not None:\n self._tensorboard.enable_activation_logging(self.model)\n\n # Using `DistributedDataParallel`(ddp) brings in a quirk wrt AllenNLP's `Model` interface and its\n # usage. A `Model` object is wrapped by `ddp`, but assigning the wrapped model to `self.model`\n # will break the usages such as `Model.get_regularization_penalty`, `Model.get_metrics`, etc.\n #\n # Hence a reference to Pytorch's object is maintained in the case of distributed training and in the\n # normal case, reference to `Model` is retained. This reference is only used in\n # these places: `model.__call__`, `model.train` and `model.eval`.\n if self._distributed:\n self._pytorch_model = DistributedDataParallel(\n self.model, device_ids=[self.cuda_device], find_unused_parameters=True\n )\n else:\n self._pytorch_model = self.model\n\n def rescale_gradients(self) -> Optional[float]:\n return training_util.rescale_gradients(self.model, self._grad_norm)\n\n def batch_loss(self, batch: TensorDict, for_training: bool) -> torch.Tensor:\n \"\"\"\n Does a forward pass on the given batches and returns the ``loss`` value in the result.\n If ``for_training`` is `True` also applies regularization penalty.\n \"\"\"\n batch = nn_util.move_to_device(batch, self.cuda_device)\n output_dict = self._pytorch_model(**batch)\n\n try:\n loss = output_dict[\"loss\"]\n if for_training:\n loss += self.model.get_regularization_penalty()\n except KeyError:\n if for_training:\n raise RuntimeError(\n \"The model you are trying to optimize does not contain a\"\n \" 'loss' key in the output of model.forward(inputs).\"\n )\n loss = None\n\n return loss\n\n def _train_epoch(self, epoch: int) -> Dict[str, float]:\n \"\"\"\n Trains one epoch and returns metrics.\n \"\"\"\n logger.info(\"Epoch %d/%d\", epoch, self._num_epochs - 1)\n peak_cpu_usage = peak_memory_mb()\n logger.info(f\"Peak CPU memory usage MB: {peak_cpu_usage}\")\n gpu_usage = []\n for gpu, memory in gpu_memory_mb().items():\n gpu_usage.append((gpu, memory))\n logger.info(f\"GPU {gpu} memory usage MB: {memory}\")\n\n train_loss = 0.0\n # Set the model to \"train\" mode.\n self._pytorch_model.train()\n\n # Get tqdm for the training batches\n batch_generator = self.iterator(self.train_data, num_epochs=1, shuffle=self.shuffle)\n batch_group_generator = lazy_groups_of(\n batch_generator, self._num_gradient_accumulation_steps\n )\n num_training_batches = math.ceil(\n self.iterator.get_num_batches(self.train_data) / self._num_gradient_accumulation_steps\n )\n # Having multiple tqdm bars in case of distributed training will be a mess. Hence only the master's\n # progress is shown\n if self._master:\n batch_group_generator_tqdm = Tqdm.tqdm(\n batch_group_generator, total=num_training_batches\n )\n else:\n batch_group_generator_tqdm = batch_group_generator\n\n self._last_log = time.time()\n last_save_time = time.time()\n\n batches_this_epoch = 0\n if self._batch_num_total is None:\n self._batch_num_total = 0\n\n histogram_parameters = set(self.model.get_parameters_for_histogram_tensorboard_logging())\n\n logger.info(\"Training\")\n\n cumulative_batch_group_size = 0\n for batch_group in batch_group_generator_tqdm:\n batches_this_epoch += 1\n self._batch_num_total += 1\n batch_num_total = self._batch_num_total\n\n self.optimizer.zero_grad()\n\n for batch in batch_group:\n loss = self.batch_loss(batch, for_training=True)\n if torch.isnan(loss):\n raise ValueError(\"nan loss encountered\")\n loss = loss / len(batch_group)\n loss.backward()\n train_loss += loss.item()\n\n batch_grad_norm = self.rescale_gradients()\n\n # This does nothing if batch_num_total is None or you are using a\n # scheduler which doesn't update per batch.\n if self._learning_rate_scheduler:\n self._learning_rate_scheduler.step_batch(batch_num_total)\n if self._momentum_scheduler:\n self._momentum_scheduler.step_batch(batch_num_total)\n\n if self._tensorboard.should_log_histograms_this_batch() and self._master:\n # get the magnitude of parameter updates for logging\n # We need a copy of current parameters to compute magnitude of updates,\n # and copy them to CPU so large models won't go OOM on the GPU.\n param_updates = {\n name: param.detach().cpu().clone()\n for name, param in self.model.named_parameters()\n }\n self.optimizer.step()\n for name, param in self.model.named_parameters():\n param_updates[name].sub_(param.detach().cpu())\n update_norm = torch.norm(param_updates[name].view(-1))\n param_norm = torch.norm(param.view(-1)).cpu()\n self._tensorboard.add_train_scalar(\n \"gradient_update/\" + name, update_norm / (param_norm + 1e-7)\n )\n else:\n self.optimizer.step()\n\n # Update moving averages\n if self._moving_average is not None:\n self._moving_average.apply(batch_num_total)\n\n # Update the description with the latest metrics\n metrics = training_util.get_metrics(\n self.model,\n train_loss,\n batches_this_epoch,\n world_size=self._world_size,\n cuda_device=[self.cuda_device],\n )\n\n # Updating tqdm only for the master as the trainers wouldn't have one\n if self._master:\n description = training_util.description_from_metrics(metrics)\n batch_group_generator_tqdm.set_description(description, refresh=False)\n\n # Log parameter values to Tensorboard (only from the master)\n if self._tensorboard.should_log_this_batch() and self._master:\n self._tensorboard.log_parameter_and_gradient_statistics(self.model, batch_grad_norm)\n self._tensorboard.log_learning_rates(self.model, self.optimizer)\n\n self._tensorboard.add_train_scalar(\"loss/loss_train\", metrics[\"loss\"])\n self._tensorboard.log_metrics({\"epoch_metrics/\" + k: v for k, v in metrics.items()})\n\n if self._tensorboard.should_log_histograms_this_batch() and self._master:\n self._tensorboard.log_histograms(self.model, histogram_parameters)\n\n if self._log_batch_size_period:\n batch_group_size = sum(training_util.get_batch_size(batch) for batch in batch_group)\n cumulative_batch_group_size += batch_group_size\n if (batches_this_epoch - 1) % self._log_batch_size_period == 0:\n average = cumulative_batch_group_size / batches_this_epoch\n logger.info(\n f\"current batch size: {batch_group_size} mean batch size: {average}\"\n )\n self._tensorboard.add_train_scalar(\"current_batch_size\", batch_group_size)\n self._tensorboard.add_train_scalar(\"mean_batch_size\", average)\n\n # Save model if needed.\n if (\n self._model_save_interval is not None\n and (time.time() - last_save_time > self._model_save_interval)\n and self._master\n ):\n last_save_time = time.time()\n self._save_checkpoint(\n \"{0}.{1}\".format(epoch, training_util.time_to_str(int(last_save_time)))\n )\n metrics = training_util.get_metrics(\n self.model,\n train_loss,\n batches_this_epoch,\n reset=True,\n world_size=self._world_size,\n cuda_device=[self.cuda_device],\n )\n metrics[\"cpu_memory_MB\"] = peak_cpu_usage\n for (gpu_num, memory) in gpu_usage:\n metrics[\"gpu_\" + str(gpu_num) + \"_memory_MB\"] = memory\n return metrics\n\n def _validation_loss(self) -> Tuple[float, int]:\n \"\"\"\n Computes the validation loss. Returns it and the number of batches.\n \"\"\"\n logger.info(\"Validating\")\n\n self._pytorch_model.eval()\n\n # Replace parameter values with the shadow values from the moving averages.\n if self._moving_average is not None:\n self._moving_average.assign_average_value()\n\n if self._validation_iterator is not None:\n val_iterator = self._validation_iterator\n else:\n val_iterator = self.iterator\n\n val_generator = val_iterator(self._validation_data, num_epochs=1, shuffle=False)\n num_validation_batches = val_iterator.get_num_batches(self._validation_data)\n val_generator_tqdm = Tqdm.tqdm(val_generator, total=num_validation_batches)\n batches_this_epoch = 0\n val_loss = 0\n for batch in val_generator_tqdm:\n\n loss = self.batch_loss(batch, for_training=False)\n if loss is not None:\n # You shouldn't necessarily have to compute a loss for validation, so we allow for\n # `loss` to be None. We need to be careful, though - `batches_this_epoch` is\n # currently only used as the divisor for the loss function, so we can safely only\n # count those batches for which we actually have a loss. If this variable ever\n # gets used for something else, we might need to change things around a bit.\n batches_this_epoch += 1\n val_loss += loss.detach().cpu().numpy()\n\n # Update the description with the latest metrics\n val_metrics = training_util.get_metrics(\n self.model,\n val_loss,\n batches_this_epoch,\n world_size=self._world_size,\n cuda_device=[self.cuda_device],\n )\n description = training_util.description_from_metrics(val_metrics)\n val_generator_tqdm.set_description(description, refresh=False)\n\n # Now restore the original parameter values.\n if self._moving_average is not None:\n self._moving_average.restore()\n\n return val_loss, batches_this_epoch\n\n def train(self) -> Dict[str, Any]:\n \"\"\"\n Trains the supplied model with the supplied parameters.\n \"\"\"\n try:\n epoch_counter = self._restore_checkpoint()\n except RuntimeError:\n traceback.print_exc()\n raise ConfigurationError(\n \"Could not recover training from the checkpoint. Did you mean to output to \"\n \"a different serialization directory or delete the existing serialization \"\n \"directory?\"\n )\n\n training_util.enable_gradient_clipping(self.model, self._grad_clipping)\n\n logger.info(\"Beginning training.\")\n\n train_metrics: Dict[str, float] = {}\n val_metrics: Dict[str, float] = {}\n this_epoch_val_metric: float = None\n metrics: Dict[str, Any] = {}\n epochs_trained = 0\n training_start_time = time.time()\n\n metrics[\"best_epoch\"] = self._metric_tracker.best_epoch\n for key, value in self._metric_tracker.best_epoch_metrics.items():\n metrics[\"best_validation_\" + key] = value\n\n for epoch in range(epoch_counter, self._num_epochs):\n epoch_start_time = time.time()\n train_metrics = self._train_epoch(epoch)\n\n # get peak of memory usage\n if \"cpu_memory_MB\" in train_metrics:\n metrics[\"peak_cpu_memory_MB\"] = max(\n metrics.get(\"peak_cpu_memory_MB\", 0), train_metrics[\"cpu_memory_MB\"]\n )\n for key, value in train_metrics.items():\n if key.startswith(\"gpu_\"):\n metrics[\"peak_\" + key] = max(metrics.get(\"peak_\" + key, 0), value)\n\n # Let all workers finish training before going into the validation mode\n if self._distributed:\n dist.barrier()\n\n if self._validation_data is not None:\n with torch.no_grad():\n # We have a validation set, so compute all the metrics on it.\n val_loss, num_batches = self._validation_loss()\n\n # It is safe again to wait till the validation is done. This is\n # important to get the metrics right.\n if self._distributed:\n dist.barrier()\n\n val_metrics = training_util.get_metrics(\n self.model,\n val_loss,\n num_batches,\n reset=True,\n world_size=self._world_size,\n cuda_device=[self.cuda_device],\n )\n\n # Check validation metric for early stopping\n this_epoch_val_metric = val_metrics[self._validation_metric]\n self._metric_tracker.add_metric(this_epoch_val_metric)\n\n if self._metric_tracker.should_stop_early():\n logger.info(\"Ran out of patience. Stopping training.\")\n break\n\n if self._master:\n self._tensorboard.log_metrics(\n train_metrics, val_metrics=val_metrics, log_to_console=True, epoch=epoch + 1\n ) # +1 because tensorboard doesn't like 0\n\n # Create overall metrics dict\n training_elapsed_time = time.time() - training_start_time\n metrics[\"training_duration\"] = str(datetime.timedelta(seconds=training_elapsed_time))\n metrics[\"training_start_epoch\"] = epoch_counter\n metrics[\"training_epochs\"] = epochs_trained\n metrics[\"epoch\"] = epoch\n\n for key, value in train_metrics.items():\n metrics[\"training_\" + key] = value\n for key, value in val_metrics.items():\n metrics[\"validation_\" + key] = value\n\n if self._metric_tracker.is_best_so_far():\n # Update all the best_ metrics.\n # (Otherwise they just stay the same as they were.)\n metrics[\"best_epoch\"] = epoch\n for key, value in val_metrics.items():\n metrics[\"best_validation_\" + key] = value\n\n self._metric_tracker.best_epoch_metrics = val_metrics\n\n if self._serialization_dir and self._master:\n dump_metrics(\n os.path.join(self._serialization_dir, f\"metrics_epoch_{epoch}.json\"), metrics\n )\n\n # The Scheduler API is agnostic to whether your schedule requires a validation metric -\n # if it doesn't, the validation metric passed here is ignored.\n if self._learning_rate_scheduler:\n self._learning_rate_scheduler.step(this_epoch_val_metric, epoch)\n if self._momentum_scheduler:\n self._momentum_scheduler.step(this_epoch_val_metric, epoch)\n\n if self._master:\n self._save_checkpoint(epoch)\n\n # Wait for the master to finish saving the checkpoint\n if self._distributed:\n dist.barrier()\n\n epoch_elapsed_time = time.time() - epoch_start_time\n logger.info(\"Epoch duration: %s\", datetime.timedelta(seconds=epoch_elapsed_time))\n\n if epoch < self._num_epochs - 1:\n training_elapsed_time = time.time() - training_start_time\n estimated_time_remaining = training_elapsed_time * (\n (self._num_epochs - epoch_counter) / float(epoch - epoch_counter + 1) - 1\n )\n formatted_time = str(datetime.timedelta(seconds=int(estimated_time_remaining)))\n logger.info(\"Estimated training time remaining: %s\", formatted_time)\n\n epochs_trained += 1\n\n # make sure pending events are flushed to disk and files are closed properly\n self._tensorboard.close()\n\n # Load the best model state before returning\n best_model_state = self._checkpointer.best_model_state()\n if best_model_state:\n self.model.load_state_dict(best_model_state)\n\n return metrics\n\n def _save_checkpoint(self, epoch: Union[int, str]) -> None:\n \"\"\"\n Saves a checkpoint of the model to self._serialization_dir.\n Is a no-op if self._serialization_dir is None.\n\n # Parameters\n\n epoch : Union[int, str], required.\n The epoch of training. If the checkpoint is saved in the middle\n of an epoch, the parameter is a string with the epoch and timestamp.\n \"\"\"\n # If moving averages are used for parameters, we save\n # the moving average values into checkpoint, instead of the current values.\n if self._moving_average is not None:\n self._moving_average.assign_average_value()\n\n # These are the training states we need to persist.\n training_states = {\n \"metric_tracker\": self._metric_tracker.state_dict(),\n \"optimizer\": self.optimizer.state_dict(),\n \"batch_num_total\": self._batch_num_total,\n }\n\n # If we have a learning rate or momentum scheduler, we should persist them too.\n if self._learning_rate_scheduler is not None:\n training_states[\"learning_rate_scheduler\"] = self._learning_rate_scheduler.state_dict()\n if self._momentum_scheduler is not None:\n training_states[\"momentum_scheduler\"] = self._momentum_scheduler.state_dict()\n\n self._checkpointer.save_checkpoint(\n model_state=self.model.state_dict(),\n epoch=epoch,\n training_states=training_states,\n is_best_so_far=self._metric_tracker.is_best_so_far(),\n )\n\n # Restore the original values for parameters so that training will not be affected.\n if self._moving_average is not None:\n self._moving_average.restore()\n\n def _restore_checkpoint(self) -> int:\n \"\"\"\n Restores the model and training state from the last saved checkpoint.\n This includes an epoch count and optimizer state, which is serialized separately\n from model parameters. This function should only be used to continue training -\n if you wish to load a model for inference/load parts of a model into a new\n computation graph, you should use the native Pytorch functions:\n `` model.load_state_dict(torch.load(\"/path/to/model/weights.th\"))``\n\n If ``self._serialization_dir`` does not exist or does not contain any checkpointed weights,\n this function will do nothing and return 0.\n\n # Returns\n\n epoch: int\n The epoch at which to resume training, which should be one after the epoch\n in the saved training state.\n \"\"\"\n model_state, training_state = self._checkpointer.restore_checkpoint()\n\n if not training_state:\n # No checkpoint to restore, start at 0\n return 0\n\n self.model.load_state_dict(model_state)\n self.optimizer.load_state_dict(training_state[\"optimizer\"])\n if (\n self._learning_rate_scheduler is not None\n and \"learning_rate_scheduler\" in training_state\n ):\n self._learning_rate_scheduler.load_state_dict(training_state[\"learning_rate_scheduler\"])\n if self._momentum_scheduler is not None and \"momentum_scheduler\" in training_state:\n self._momentum_scheduler.load_state_dict(training_state[\"momentum_scheduler\"])\n training_util.move_optimizer_to_cuda(self.optimizer)\n\n # Currently the ``training_state`` contains a serialized ``MetricTracker``.\n if \"metric_tracker\" in training_state:\n self._metric_tracker.load_state_dict(training_state[\"metric_tracker\"])\n # It used to be the case that we tracked ``val_metric_per_epoch``.\n elif \"val_metric_per_epoch\" in training_state:\n self._metric_tracker.clear()\n self._metric_tracker.add_metrics(training_state[\"val_metric_per_epoch\"])\n # And before that we didn't track anything.\n else:\n self._metric_tracker.clear()\n\n if isinstance(training_state[\"epoch\"], int):\n epoch_to_return = training_state[\"epoch\"] + 1\n else:\n epoch_to_return = int(training_state[\"epoch\"].split(\".\")[0]) + 1\n\n # For older checkpoints with batch_num_total missing, default to old behavior where\n # it is unchanged.\n batch_num_total = training_state.get(\"batch_num_total\")\n if batch_num_total is not None:\n self._batch_num_total = batch_num_total\n\n return epoch_to_return\n\n # Requires custom from_params.\n @classmethod\n def from_params( # type: ignore\n cls,\n model: Model,\n serialization_dir: str,\n iterator: DataIterator,\n train_data: Iterable[Instance],\n validation_data: Optional[Iterable[Instance]],\n params: Params,\n validation_iterator: DataIterator = None,\n local_rank: int = 0,\n ) -> \"Trainer\":\n\n patience = params.pop_int(\"patience\", None)\n validation_metric = params.pop(\"validation_metric\", \"-loss\")\n shuffle = params.pop_bool(\"shuffle\", True)\n num_epochs = params.pop_int(\"num_epochs\", 20)\n cuda_device = parse_cuda_device(params.pop(\"cuda_device\", -1))\n grad_norm = params.pop_float(\"grad_norm\", None)\n grad_clipping = params.pop_float(\"grad_clipping\", None)\n lr_scheduler_params = params.pop(\"learning_rate_scheduler\", None)\n momentum_scheduler_params = params.pop(\"momentum_scheduler\", None)\n\n check_for_gpu(cuda_device)\n if cuda_device >= 0:\n # Moving model to GPU here so that the optimizer state gets constructed on\n # the right device.\n model = model.cuda(cuda_device)\n\n parameters = [[n, p] for n, p in model.named_parameters() if p.requires_grad]\n optimizer = Optimizer.from_params(parameters, params.pop(\"optimizer\"))\n if \"moving_average\" in params:\n moving_average = MovingAverage.from_params(\n params.pop(\"moving_average\"), parameters=parameters\n )\n else:\n moving_average = None\n\n if lr_scheduler_params:\n lr_scheduler = LearningRateScheduler.from_params(optimizer, lr_scheduler_params)\n else:\n lr_scheduler = None\n if momentum_scheduler_params:\n momentum_scheduler = MomentumScheduler.from_params(optimizer, momentum_scheduler_params)\n else:\n momentum_scheduler = None\n\n if \"checkpointer\" in params:\n if (\n \"keep_serialized_model_every_num_seconds\" in params\n or \"num_serialized_models_to_keep\" in params\n ):\n raise ConfigurationError(\n \"Checkpointer may be initialized either from the 'checkpointer' key or from the \"\n \"keys 'num_serialized_models_to_keep' and 'keep_serialized_model_every_num_seconds'\"\n \" but the passed config uses both methods.\"\n )\n checkpointer = Checkpointer.from_params(params.pop(\"checkpointer\"))\n else:\n num_serialized_models_to_keep = params.pop_int(\"num_serialized_models_to_keep\", 20)\n keep_serialized_model_every_num_seconds = params.pop_int(\n \"keep_serialized_model_every_num_seconds\", None\n )\n checkpointer = Checkpointer(\n serialization_dir=serialization_dir,\n num_serialized_models_to_keep=num_serialized_models_to_keep,\n keep_serialized_model_every_num_seconds=keep_serialized_model_every_num_seconds,\n )\n model_save_interval = params.pop_float(\"model_save_interval\", None)\n summary_interval = params.pop_int(\"summary_interval\", 100)\n histogram_interval = params.pop_int(\"histogram_interval\", None)\n should_log_parameter_statistics = params.pop_bool(\"should_log_parameter_statistics\", True)\n should_log_learning_rate = params.pop_bool(\"should_log_learning_rate\", False)\n log_batch_size_period = params.pop_int(\"log_batch_size_period\", None)\n\n distributed = params.pop_bool(\"distributed\", False)\n world_size = params.pop_int(\"world_size\", 1)\n\n num_gradient_accumulation_steps = params.pop(\"num_gradient_accumulation_steps\", 1)\n\n params.assert_empty(cls.__name__)\n return cls(\n model,\n optimizer,\n iterator,\n train_data,\n validation_data,\n patience=patience,\n validation_metric=validation_metric,\n validation_iterator=validation_iterator,\n shuffle=shuffle,\n num_epochs=num_epochs,\n serialization_dir=serialization_dir,\n cuda_device=cuda_device,\n grad_norm=grad_norm,\n grad_clipping=grad_clipping,\n learning_rate_scheduler=lr_scheduler,\n momentum_scheduler=momentum_scheduler,\n checkpointer=checkpointer,\n model_save_interval=model_save_interval,\n summary_interval=summary_interval,\n histogram_interval=histogram_interval,\n should_log_parameter_statistics=should_log_parameter_statistics,\n should_log_learning_rate=should_log_learning_rate,\n log_batch_size_period=log_batch_size_period,\n moving_average=moving_average,\n distributed=distributed,\n rank=local_rank,\n world_size=world_size,\n num_gradient_accumulation_steps=num_gradient_accumulation_steps,\n )\n"
] | [
[
"torch.isnan",
"torch.nn.parallel.DistributedDataParallel",
"torch.no_grad",
"torch.distributed.barrier"
]
] |
PDillis/coiltraine | [
"a682aa62af5f6ecb95a837d33b70d893d3d261f6"
] | [
"network/models/coil_reverse.py"
] | [
"from logger import coil_logger\nimport torch.nn as nn\nimport torch\nimport importlib\n\nfrom configs import g_conf\nfrom coilutils.general import command_number_to_index\n\nfrom .building_blocks import Conv\nfrom .building_blocks import Branching\nfrom .building_blocks import FC\nfrom .building_blocks import Join\nfrom .building_blocks import ReverseLayerFunction\n\n\nclass CoILReverse(nn.Module):\n\n def __init__(self, params, sensors):\n\n super(CoILReverse, self).__init__()\n self.params = params\n\n number_first_layer_channels = 0\n\n # If we fuse more than one frame, then the first layer will be a concatenation of\n # the channels of this first layer [3, w, h] (e.g., 2 RGB images->3+3=6)\n for _, sizes in g_conf.SENSORS.items():\n number_first_layer_channels += sizes[0] * g_conf.NUMBER_FRAMES_FUSION\n\n # Get one item from the dict\n sensor_input_shape = next(iter(g_conf.SENSORS.values())) # [3, 300, 400]\n sensor_input_shape = [number_first_layer_channels, sensor_input_shape[1],\n sensor_input_shape[2]] # replace the above result on the channels here\n\n # For this case we check if the perception layer is of the type \"conv\"\n if 'conv' in params['perception']:\n perception_convs = Conv(params={\n 'channels': [number_first_layer_channels] + params['perception']['conv']['channels'],\n 'kernels': params['perception']['conv']['kernels'],\n 'strides': params['perception']['conv']['strides'],\n 'dropouts': params['perception']['conv']['dropouts'],\n 'end_layer': True})\n\n perception_fc = FC(params={\n 'neurons': [perception_convs.get_conv_output(sensor_input_shape)] + params['perception']['fc']['neurons'],\n 'dropouts': params['perception']['fc']['dropouts'],\n 'end_layer': False})\n\n self.perception = nn.Sequential(*[perception_convs, perception_fc])\n\n number_output_neurons = params['perception']['fc']['neurons'][-1]\n\n elif 'res' in params['perception']: # pre defined residual networks\n resnet_module = importlib.import_module('network.models.building_blocks.resnet')\n resnet_module = getattr(resnet_module, params['perception']['res']['name'])\n self.perception = resnet_module(pretrained=g_conf.PRE_TRAINED,\n num_classes=params['perception']['res']['num_classes'],\n img_h=sensors['rgb'][1],\n img_w=sensors['rgb'][2])\n\n number_output_neurons = params['perception']['res']['num_classes']\n\n else:\n\n raise ValueError(\"Invalid perception layer type; only convolutional ('conv') or ResNet-based ('res') \"\n \"are allowed)\")\n\n self.intermediate_layers = None\n\n self.measurements = FC(params={'neurons': [len(g_conf.INPUTS)] + params['measurements']['fc']['neurons'],\n 'dropouts': params['measurements']['fc']['dropouts'],\n 'end_layer': False})\n\n self.join = Join(\n params={\n 'after_process': FC(params={\n 'neurons': [params['measurements']['fc']['neurons'][-1] + number_output_neurons] +\n params['join']['fc']['neurons'],\n 'dropouts': params['join']['fc']['dropouts'],\n 'end_layer': False}),\n 'mode': 'cat'})\n\n self.speed_branch = FC(params={\n 'neurons': [params['join']['fc']['neurons'][-1]] + params['speed_branch']['fc']['neurons'] + [1],\n 'dropouts': params['speed_branch']['fc']['dropouts'] + [0.0],\n 'end_layer': True})\n\n # Create the fc vector separately\n branch_fc_vector = []\n for i in range(params['branches']['number_of_branches']):\n branch_fc_vector.append(FC(params={'neurons': [params['join']['fc']['neurons'][-1]] +\n params['branches']['fc']['neurons'] + [len(g_conf.TARGETS)],\n 'dropouts': params['branches']['fc']['dropouts'] + [0.0],\n 'end_layer': True}))\n\n self.branches = Branching(branch_fc_vector) # Here we set branching automatically\n\n # Weight initialization for the convolutional perception modules\n if 'conv' in params['perception']:\n for m in self.modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):\n nn.init.xavier_uniform_(m.weight)\n nn.init.constant_(m.bias, 0.1)\n # Init for the rest of the network\n else:\n for m in self.modules():\n if isinstance(m, nn.Linear):\n nn.init.xavier_uniform_(m.weight)\n nn.init.constant_(m.bias, 0.1)\n\n def forward(self, x, a):\n \"\"\" ###### APPLY THE PERCEPTION MODULE \"\"\"\n x, self.intermediate_layers = self.perception(x)\n # Not a variable, just to store intermediate layers for future visualization\n # self.intermediate_layers = inter\n\n \"\"\" APPLY THE MEASUREMENT MODULE \"\"\"\n m = self.measurements(a)\n \"\"\" Join measurements and perception\"\"\"\n j = self.join(x, m)\n\n branch_outputs = self.branches(j)\n\n speed_branch_output = self.speed_branch(x)\n\n # We concatenate speed with the rest.\n return branch_outputs + [speed_branch_output]\n\n def forward_branch(self, x, a, branch_number):\n \"\"\"\n Do a forward operation and return a single branch.\n\n Args:\n x: the image input (torch.squeeze(data['rgb']))\n a: speed measurement (dataset.extract_inputs(data))\n branch_number: the branch number to be returned (data['directions'])\n\n Returns:\n the forward operation on the selected branch\n\n \"\"\"\n output_vec = torch.stack(self.forward(x, a)[0:self.params['branches']['number_of_branches']])\n\n return self.extract_branch(output_vec, branch_number)\n\n def get_perception_layers(self, x):\n return self.perception.get_layers_features(x)\n\n @staticmethod\n def extract_branch(output_vec, branch_number):\n # Extract\n branch_number = command_number_to_index(branch_number)\n\n if len(branch_number) > 1:\n branch_number = torch.squeeze(branch_number.type(torch.cuda.LongTensor))\n else:\n branch_number = branch_number.type(torch.cuda.LongTensor)\n\n branch_number = torch.stack([branch_number, torch.cuda.LongTensor(range(0, len(branch_number)))])\n\n return output_vec[branch_number[0], branch_number[1], :]\n"
] | [
[
"torch.nn.init.xavier_uniform_",
"torch.nn.Sequential",
"torch.nn.init.constant_"
]
] |
thundergolfer/text-classify-with-cnn | [
"02fe7b3f85a5408f38f1fbc97382d41e80b78ff8"
] | [
"evaluate.py"
] | [
"# coding: utf-8\n\n\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport time\nimport datetime\nimport manage_data\nfrom text_network import TextNetwork\nfrom tensorflow.contrib import learn\n\n\n# ### Set Params\n\n# Eval Parameters\ntf.flags.DEFINE_integer(\"batch_size\", 64, \"Batch Size (default: 64)\")\ntf.flags.DEFINE_string(\"checkpoint_dir\", \"\", \"Checkpoint directory from training run\")\ntf.flags.DEFINE_boolean(\"eval_train\", False, \"Evaluate on all training data\")\n\n# Misc Parameters\ntf.flags.DEFINE_boolean(\"allow_soft_placement\", True, \"Allow device soft device placement\")\ntf.flags.DEFINE_boolean(\"log_device_placement\", False, \"Log placement of ops on devices\")\n\n\nFLAGS = tf.flags.FLAGS\nFLAGS._parse_flags()\nprint(\"\\nParameters:\")\nfor attr, value in sorted(FLAGS.__flags.items()):\n print(\"{}={}\".format(attr.upper(), value))\nprint(\"\")\n\n# CHANGE THIS: Load data. Load your own data here\nif FLAGS.eval_train:\n x_raw, y_test = manage_data.load_data_and_labels()\n y_test = np.argmax(y_test, axis=1)\nelse:\n x_raw = [\"a masterpiece four years in the making\", \"everything is off.\"]\n y_test = [1, 0]\n\n# Map data into vocabulary\nvocab_path = os.path.join(FLAGS.checkpoint_dir, \"..\", \"vocab\")\nvocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path)\nx_test = np.array(list(vocab_processor.transform(x_raw)))\n\nprint(\"\\nEvaluating...\\n\")\n\n\n# ### Evaluation\n\n\ncheckpoint_file = tf.train.latest_checkpoint(FLAGS.checkpoint_dir)\ngraph = tf.Graph()\nwith graph.as_default():\n session_conf = tf.ConfigProto(\n allow_soft_placement=FLAGS.allow_soft_placement,\n log_device_placement=FLAGS.log_device_placement)\n sess = tf.Session(config=session_conf)\n with sess.as_default():\n # Load the saved meta graph and restore variables\n saver = tf.train.import_meta_graph(\"{}.meta\".format(checkpoint_file))\n saver.restore(sess, checkpoint_file)\n\n # Get the placeholders from the graph by name\n input_x = graph.get_operation_by_name(\"input_x\").outputs[0]\n # input_y = graph.get_operation_by_name(\"input_y\").outputs[0]\n dropout_keep_prob = graph.get_operation_by_name(\"dropout_keep_prob\").outputs[0]\n\n # Tensors we want to evaluate\n predictions = graph.get_operation_by_name(\"output/predictions\").outputs[0]\n\n # Generate batches for one epoch\n batches = manage_data.batch_iter(list(x_test), FLAGS.batch_size, 1, shuffle=False)\n\n # Collect the predictions here\n all_predictions = []\n\n for x_test_batch in batches:\n batch_predictions = sess.run(predictions, {input_x: x_test_batch, dropout_keep_prob: 1.0})\n all_predictions = np.concatenate([all_predictions, batch_predictions])\n\n# Print accuracy if y_test is defined\nif y_test is not None:\n correct_predictions = float(sum(all_predictions == y_test))\n print(\"Total number of test examples: {}\".format(len(y_test)))\n print(\"Accuracy: {:g}\".format(correct_predictions/float(len(y_test))))\n"
] | [
[
"tensorflow.flags.DEFINE_integer",
"tensorflow.contrib.learn.preprocessing.VocabularyProcessor.restore",
"numpy.argmax",
"tensorflow.Graph",
"tensorflow.train.latest_checkpoint",
"tensorflow.flags.DEFINE_boolean",
"tensorflow.Session",
"tensorflow.flags.DEFINE_string",
"numpy.concatenate",
"tensorflow.ConfigProto"
]
] |
Radiian-Arts-Main/Radiian-Arts-BioSource | [
"51e08da0b3171fe96badc68780fd0f3381d49738"
] | [
"makehuman-master/makehuman/apps/autoskinblender.py"
] | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n**Project Name:** MakeHuman\n\n**Product Home Page:** http://www.makehumancommunity.org/\n\n**Github Code Home Page:** https://github.com/makehumancommunity/\n\n**Authors:** Jonas Hauquier\n\n**Copyright(c):** MakeHuman Team 2001-2019\n\n**Licensing:** AGPL3\n\n This file is part of MakeHuman Community (www.makehumancommunity.org).\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n\nAbstract\n--------\n\nBlend skin and color properties based on human ethnic values\n\"\"\"\n\nimport material\nimport image\nimport image_operations\nimport numpy as np\nfrom getpath import getSysDataPath\n\n\nasianColor = np.asarray([0.721, 0.568, 0.431], dtype=np.float32)\nafricanColor = np.asarray([0.207, 0.113, 0.066], dtype=np.float32)\ncaucasianColor = np.asarray([0.843, 0.639, 0.517], dtype=np.float32)\n\nclass EthnicSkinBlender(object):\n \"\"\"\n Skin blender for the adaptive_skin_tone litsphere texture. Makes sure that\n the texture is set to a blend of the three ethnic skin tones based on the\n human macro settings.\n \"\"\"\n def __init__(self, human):\n self.human = human\n self.skinCache = { 'caucasian' : image.Image(getSysDataPath('litspheres/skinmat_caucasian.png')),\n 'african' : image.Image(getSysDataPath('litspheres/skinmat_african.png')),\n 'asian' : image.Image(getSysDataPath('litspheres/skinmat_asian.png')) }\n self._previousEthnicState = [0, 0, 0]\n\n self._litsphereTexture = None\n self._diffuseColor = material.Color()\n\n self.checkUpdate()\n\n def checkUpdate(self):\n newEthnicState = self.getEthnicState()\n if self._previousEthnicState != newEthnicState:\n self.update()\n self._previousEthnicState = newEthnicState\n return True\n return False\n\n def getEthnicState(self):\n return [ self.human.getCaucasian(),\n self.human.getAfrican(),\n self.human.getAsian() ]\n\n def getLitsphereTexture(self):\n self.checkUpdate()\n return self._litsphereTexture\n\n def getDiffuseColor(self):\n self.checkUpdate()\n return self._diffuseColor\n\n def update(self):\n caucasianWeight = self.human.getCaucasian()\n africanWeight = self.human.getAfrican()\n asianWeight = self.human.getAsian()\n blends = []\n\n # Set litsphere texture\n if caucasianWeight > 0:\n blends.append( ('caucasian', caucasianWeight) )\n if africanWeight > 0:\n blends.append( ('african', africanWeight) )\n if asianWeight > 0:\n blends.append( ('asian', asianWeight) )\n\n if len(blends) == 1:\n img = self.skinCache[blends[0][0]]\n img.markModified()\n else:\n img = image_operations.mix(self.skinCache[blends[0][0]], self.skinCache[blends[1][0]], blends[0][1], blends[1][1])\n if len(blends) > 2:\n img = image_operations.mix(img, self.skinCache[blends[2][0]], 1.0, blends[2][1])\n\n # Set parameter so the image can be referenced when material is written to file (and texture can be cached)\n img.sourcePath = getSysDataPath(\"litspheres/adaptive_skin_tone.png\")\n self._litsphereTexture = img\n\n # Set diffuse color\n diffuse = asianWeight * asianColor + \\\n africanWeight * africanColor + \\\n caucasianWeight * caucasianColor\n self._diffuseColor = material.Color(diffuse)\n\n"
] | [
[
"numpy.asarray"
]
] |
Dynmi/tensorflow | [
"74f953df1b3a3e2f32ffdd0065322a0aa9df53e2"
] | [
"tensorflow/python/keras/losses.py"
] | [
"# Copyright 2015 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\"\"\"Built-in loss functions.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport abc\n\nimport six\n\nfrom tensorflow.python.autograph.core import ag_ctx\nfrom tensorflow.python.autograph.impl import api as autograph\nfrom tensorflow.python.distribute import distribution_strategy_context\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import smart_cond\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.keras.utils import losses_utils\nfrom tensorflow.python.keras.utils import tf_utils\nfrom tensorflow.python.keras.utils.generic_utils import deserialize_keras_object\nfrom tensorflow.python.keras.utils.generic_utils import serialize_keras_object\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn\nfrom tensorflow.python.ops.losses import losses_impl\nfrom tensorflow.python.util import dispatch\nfrom tensorflow.python.util.tf_export import keras_export\nfrom tensorflow.tools.docs import doc_controls\n\n\n@keras_export('keras.losses.Loss')\nclass Loss(object):\n \"\"\"Loss base class.\n\n To be implemented by subclasses:\n * `call()`: Contains the logic for loss calculation using `y_true`, `y_pred`.\n\n Example subclass implementation:\n\n ```python\n class MeanSquaredError(Loss):\n\n def call(self, y_true, y_pred):\n y_pred = tf.convert_to_tensor_v2(y_pred)\n y_true = tf.cast(y_true, y_pred.dtype)\n return tf.reduce_mean(math_ops.square(y_pred - y_true), axis=-1)\n ```\n\n When used with `tf.distribute.Strategy`, outside of built-in training loops\n such as `tf.keras` `compile` and `fit`, please use 'SUM' or 'NONE' reduction\n types, and reduce losses explicitly in your training loop. Using 'AUTO' or\n 'SUM_OVER_BATCH_SIZE' will raise an error.\n\n Please see this custom training [tutorial](\n https://www.tensorflow.org/tutorials/distribute/custom_training) for more\n details on this.\n\n You can implement 'SUM_OVER_BATCH_SIZE' using global batch size like:\n ```python\n with strategy.scope():\n loss_obj = tf.keras.losses.CategoricalCrossentropy(\n reduction=tf.keras.losses.Reduction.NONE)\n ....\n loss = (tf.reduce_sum(loss_obj(labels, predictions)) *\n (1. / global_batch_size))\n ```\n \"\"\"\n\n def __init__(self, reduction=losses_utils.ReductionV2.AUTO, name=None):\n \"\"\"Initializes `Loss` class.\n\n Args:\n reduction: (Optional) Type of `tf.keras.losses.Reduction` to apply to\n loss. Default value is `AUTO`. `AUTO` indicates that the reduction\n option will be determined by the usage context. For almost all cases\n this defaults to `SUM_OVER_BATCH_SIZE`. When used with\n `tf.distribute.Strategy`, outside of built-in training loops such as\n `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`\n will raise an error. Please see this custom training [tutorial](\n https://www.tensorflow.org/tutorials/distribute/custom_training)\n for more details.\n name: Optional name for the op.\n \"\"\"\n losses_utils.ReductionV2.validate(reduction)\n self.reduction = reduction\n self.name = name\n # SUM_OVER_BATCH is only allowed in losses managed by `fit` or\n # CannedEstimators.\n self._allow_sum_over_batch_size = False\n self._set_name_scope()\n\n def _set_name_scope(self):\n \"\"\"Creates a valid `name_scope` name.\"\"\"\n if self.name is None:\n self._name_scope = self.__class__.__name__\n elif self.name == '<lambda>':\n self._name_scope = 'lambda'\n else:\n # E.g. '_my_loss' => 'my_loss'\n self._name_scope = self.name.strip('_')\n\n def __call__(self, y_true, y_pred, sample_weight=None):\n \"\"\"Invokes the `Loss` instance.\n\n Args:\n y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`, except\n sparse loss functions such as sparse categorical crossentropy where\n shape = `[batch_size, d0, .. dN-1]`\n y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`\n sample_weight: Optional `sample_weight` acts as a\n coefficient for the loss. If a scalar is provided, then the loss is\n simply scaled by the given value. If `sample_weight` is a tensor of size\n `[batch_size]`, then the total loss for each sample of the batch is\n rescaled by the corresponding element in the `sample_weight` vector. If\n the shape of `sample_weight` is `[batch_size, d0, .. dN-1]` (or can be\n broadcasted to this shape), then each loss element of `y_pred` is scaled\n by the corresponding value of `sample_weight`. (Note on`dN-1`: all loss\n functions reduce by 1 dimension, usually axis=-1.)\n\n Returns:\n Weighted loss float `Tensor`. If `reduction` is `NONE`, this has\n shape `[batch_size, d0, .. dN-1]`; otherwise, it is scalar. (Note `dN-1`\n because all loss functions reduce by 1 dimension, usually axis=-1.)\n\n Raises:\n ValueError: If the shape of `sample_weight` is invalid.\n \"\"\"\n # If we are wrapping a lambda function strip '<>' from the name as it is not\n # accepted in scope name.\n graph_ctx = tf_utils.graph_context_for_symbolic_tensors(\n y_true, y_pred, sample_weight)\n with K.name_scope(self._name_scope), graph_ctx:\n ag_call = autograph.tf_convert(self.call, ag_ctx.control_status_ctx())\n losses = ag_call(y_true, y_pred)\n return losses_utils.compute_weighted_loss(\n losses, sample_weight, reduction=self._get_reduction())\n\n @classmethod\n def from_config(cls, config):\n \"\"\"Instantiates a `Loss` from its config (output of `get_config()`).\n\n Args:\n config: Output of `get_config()`.\n\n Returns:\n A `Loss` instance.\n \"\"\"\n return cls(**config)\n\n def get_config(self):\n \"\"\"Returns the config dictionary for a `Loss` instance.\"\"\"\n return {'reduction': self.reduction, 'name': self.name}\n\n @abc.abstractmethod\n @doc_controls.for_subclass_implementers\n def call(self, y_true, y_pred):\n \"\"\"Invokes the `Loss` instance.\n\n Args:\n y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`, except\n sparse loss functions such as sparse categorical crossentropy where\n shape = `[batch_size, d0, .. dN-1]`\n y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`\n\n Returns:\n Loss values with the shape `[batch_size, d0, .. dN-1]`.\n \"\"\"\n NotImplementedError('Must be implemented in subclasses.')\n\n def _get_reduction(self):\n \"\"\"Handles `AUTO` reduction cases and returns the reduction value.\"\"\"\n if (not self._allow_sum_over_batch_size and\n distribution_strategy_context.has_strategy() and\n (self.reduction == losses_utils.ReductionV2.AUTO or\n self.reduction == losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE)):\n raise ValueError(\n 'Please use `tf.keras.losses.Reduction.SUM` or '\n '`tf.keras.losses.Reduction.NONE` for loss reduction when losses are '\n 'used with `tf.distribute.Strategy` outside of the built-in training '\n 'loops. You can implement '\n '`tf.keras.losses.Reduction.SUM_OVER_BATCH_SIZE` using global batch '\n 'size like:\\n```\\nwith strategy.scope():\\n'\n ' loss_obj = tf.keras.losses.CategoricalCrossentropy('\n 'reduction=tf.keras.losses.Reduction.NONE)\\n....\\n'\n ' loss = tf.reduce_sum(loss_obj(labels, predictions)) * '\n '(1. / global_batch_size)\\n```\\nPlease see '\n 'https://www.tensorflow.org/tutorials/distribute/custom_training'\n ' for more details.')\n\n if self.reduction == losses_utils.ReductionV2.AUTO:\n return losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE\n return self.reduction\n\n\nclass LossFunctionWrapper(Loss):\n \"\"\"Wraps a loss function in the `Loss` class.\"\"\"\n\n def __init__(self,\n fn,\n reduction=losses_utils.ReductionV2.AUTO,\n name=None,\n **kwargs):\n \"\"\"Initializes `LossFunctionWrapper` class.\n\n Args:\n fn: The loss function to wrap, with signature `fn(y_true, y_pred,\n **kwargs)`.\n reduction: (Optional) Type of `tf.keras.losses.Reduction` to apply to\n loss. Default value is `AUTO`. `AUTO` indicates that the reduction\n option will be determined by the usage context. For almost all cases\n this defaults to `SUM_OVER_BATCH_SIZE`. When used with\n `tf.distribute.Strategy`, outside of built-in training loops such as\n `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`\n will raise an error. Please see this custom training [tutorial](\n https://www.tensorflow.org/tutorials/distribute/custom_training)\n for more details.\n name: (Optional) name for the loss.\n **kwargs: The keyword arguments that are passed on to `fn`.\n \"\"\"\n super(LossFunctionWrapper, self).__init__(reduction=reduction, name=name)\n self.fn = fn\n self._fn_kwargs = kwargs\n\n def call(self, y_true, y_pred):\n \"\"\"Invokes the `LossFunctionWrapper` instance.\n\n Args:\n y_true: Ground truth values.\n y_pred: The predicted values.\n\n Returns:\n Loss values per sample.\n \"\"\"\n if tensor_util.is_tensor(y_pred) and tensor_util.is_tensor(y_true):\n y_pred, y_true = losses_utils.squeeze_or_expand_dimensions(\n y_pred, y_true)\n ag_fn = autograph.tf_convert(self.fn, ag_ctx.control_status_ctx())\n return ag_fn(y_true, y_pred, **self._fn_kwargs)\n\n def get_config(self):\n config = {}\n for k, v in six.iteritems(self._fn_kwargs):\n config[k] = K.eval(v) if tf_utils.is_tensor_or_variable(v) else v\n base_config = super(LossFunctionWrapper, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@keras_export('keras.losses.MeanSquaredError')\nclass MeanSquaredError(LossFunctionWrapper):\n \"\"\"Computes the mean of squares of errors between labels and predictions.\n\n `loss = square(y_true - y_pred)`\n\n Standalone usage:\n\n >>> y_true = [[0., 1.], [0., 0.]]\n >>> y_pred = [[1., 1.], [1., 0.]]\n >>> # Using 'auto'/'sum_over_batch_size' reduction type.\n >>> mse = tf.keras.losses.MeanSquaredError()\n >>> mse(y_true, y_pred).numpy()\n 0.5\n\n >>> # Calling with 'sample_weight'.\n >>> mse(y_true, y_pred, sample_weight=[0.7, 0.3]).numpy()\n 0.25\n\n >>> # Using 'sum' reduction type.\n >>> mse = tf.keras.losses.MeanSquaredError(\n ... reduction=tf.keras.losses.Reduction.SUM)\n >>> mse(y_true, y_pred).numpy()\n 1.0\n\n >>> # Using 'none' reduction type.\n >>> mse = tf.keras.losses.MeanSquaredError(\n ... reduction=tf.keras.losses.Reduction.NONE)\n >>> mse(y_true, y_pred).numpy()\n array([0.5, 0.5], dtype=float32)\n\n Usage with the `compile()` API:\n\n ```python\n model.compile(optimizer='sgd', loss=tf.keras.losses.MeanSquaredError())\n ```\n \"\"\"\n\n def __init__(self,\n reduction=losses_utils.ReductionV2.AUTO,\n name='mean_squared_error'):\n \"\"\"Initializes `MeanSquaredError` instance.\n\n Args:\n reduction: (Optional) Type of `tf.keras.losses.Reduction` to apply to\n loss. Default value is `AUTO`. `AUTO` indicates that the reduction\n option will be determined by the usage context. For almost all cases\n this defaults to `SUM_OVER_BATCH_SIZE`. When used with\n `tf.distribute.Strategy`, outside of built-in training loops such as\n `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`\n will raise an error. Please see this custom training [tutorial](\n https://www.tensorflow.org/tutorials/distribute/custom_training)\n for more details.\n name: Optional name for the op. Defaults to 'mean_squared_error'.\n \"\"\"\n super(MeanSquaredError, self).__init__(\n mean_squared_error, name=name, reduction=reduction)\n\n\n@keras_export('keras.losses.MeanAbsoluteError')\nclass MeanAbsoluteError(LossFunctionWrapper):\n \"\"\"Computes the mean of absolute difference between labels and predictions.\n\n `loss = abs(y_true - y_pred)`\n\n Standalone usage:\n\n >>> y_true = [[0., 1.], [0., 0.]]\n >>> y_pred = [[1., 1.], [1., 0.]]\n >>> # Using 'auto'/'sum_over_batch_size' reduction type.\n >>> mae = tf.keras.losses.MeanAbsoluteError()\n >>> mae(y_true, y_pred).numpy()\n 0.5\n\n >>> # Calling with 'sample_weight'.\n >>> mae(y_true, y_pred, sample_weight=[0.7, 0.3]).numpy()\n 0.25\n\n >>> # Using 'sum' reduction type.\n >>> mae = tf.keras.losses.MeanAbsoluteError(\n ... reduction=tf.keras.losses.Reduction.SUM)\n >>> mae(y_true, y_pred).numpy()\n 1.0\n\n >>> # Using 'none' reduction type.\n >>> mae = tf.keras.losses.MeanAbsoluteError(\n ... reduction=tf.keras.losses.Reduction.NONE)\n >>> mae(y_true, y_pred).numpy()\n array([0.5, 0.5], dtype=float32)\n\n Usage with the `compile()` API:\n\n ```python\n model.compile(optimizer='sgd', loss=tf.keras.losses.MeanAbsoluteError())\n ```\n \"\"\"\n\n def __init__(self,\n reduction=losses_utils.ReductionV2.AUTO,\n name='mean_absolute_error'):\n \"\"\"Initializes `MeanAbsoluteError` instance.\n\n Args:\n reduction: (Optional) Type of `tf.keras.losses.Reduction` to apply to\n loss. Default value is `AUTO`. `AUTO` indicates that the reduction\n option will be determined by the usage context. For almost all cases\n this defaults to `SUM_OVER_BATCH_SIZE`. When used with\n `tf.distribute.Strategy`, outside of built-in training loops such as\n `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`\n will raise an error. Please see this custom training [tutorial](\n https://www.tensorflow.org/tutorials/distribute/custom_training)\n for more details.\n name: Optional name for the op. Defaults to 'mean_absolute_error'.\n \"\"\"\n super(MeanAbsoluteError, self).__init__(\n mean_absolute_error, name=name, reduction=reduction)\n\n\n@keras_export('keras.losses.MeanAbsolutePercentageError')\nclass MeanAbsolutePercentageError(LossFunctionWrapper):\n \"\"\"Computes the mean absolute percentage error between `y_true` and `y_pred`.\n\n `loss = 100 * abs(y_true - y_pred) / y_true`\n\n Standalone usage:\n\n >>> y_true = [[2., 1.], [2., 3.]]\n >>> y_pred = [[1., 1.], [1., 0.]]\n >>> # Using 'auto'/'sum_over_batch_size' reduction type.\n >>> mape = tf.keras.losses.MeanAbsolutePercentageError()\n >>> mape(y_true, y_pred).numpy()\n 50.\n\n >>> # Calling with 'sample_weight'.\n >>> mape(y_true, y_pred, sample_weight=[0.7, 0.3]).numpy()\n 20.\n\n >>> # Using 'sum' reduction type.\n >>> mape = tf.keras.losses.MeanAbsolutePercentageError(\n ... reduction=tf.keras.losses.Reduction.SUM)\n >>> mape(y_true, y_pred).numpy()\n 100.\n\n >>> # Using 'none' reduction type.\n >>> mape = tf.keras.losses.MeanAbsolutePercentageError(\n ... reduction=tf.keras.losses.Reduction.NONE)\n >>> mape(y_true, y_pred).numpy()\n array([25., 75.], dtype=float32)\n\n Usage with the `compile()` API:\n\n ```python\n model.compile(optimizer='sgd',\n loss=tf.keras.losses.MeanAbsolutePercentageError())\n ```\n \"\"\"\n\n def __init__(self,\n reduction=losses_utils.ReductionV2.AUTO,\n name='mean_absolute_percentage_error'):\n \"\"\"Initializes `MeanAbsolutePercentageError` instance.\n\n Args:\n reduction: (Optional) Type of `tf.keras.losses.Reduction` to apply to\n loss. Default value is `AUTO`. `AUTO` indicates that the reduction\n option will be determined by the usage context. For almost all cases\n this defaults to `SUM_OVER_BATCH_SIZE`. When used with\n `tf.distribute.Strategy`, outside of built-in training loops such as\n `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`\n will raise an error. Please see this custom training [tutorial](\n https://www.tensorflow.org/tutorials/distribute/custom_training)\n for more details.\n name: Optional name for the op. Defaults to\n 'mean_absolute_percentage_error'.\n \"\"\"\n super(MeanAbsolutePercentageError, self).__init__(\n mean_absolute_percentage_error, name=name, reduction=reduction)\n\n\n@keras_export('keras.losses.MeanSquaredLogarithmicError')\nclass MeanSquaredLogarithmicError(LossFunctionWrapper):\n \"\"\"Computes the mean squared logarithmic error between `y_true` and `y_pred`.\n\n `loss = square(log(y_true + 1.) - log(y_pred + 1.))`\n\n Standalone usage:\n\n >>> y_true = [[0., 1.], [0., 0.]]\n >>> y_pred = [[1., 1.], [1., 0.]]\n >>> # Using 'auto'/'sum_over_batch_size' reduction type.\n >>> msle = tf.keras.losses.MeanSquaredLogarithmicError()\n >>> msle(y_true, y_pred).numpy()\n 0.240\n\n >>> # Calling with 'sample_weight'.\n >>> msle(y_true, y_pred, sample_weight=[0.7, 0.3]).numpy()\n 0.120\n\n >>> # Using 'sum' reduction type.\n >>> msle = tf.keras.losses.MeanSquaredLogarithmicError(\n ... reduction=tf.keras.losses.Reduction.SUM)\n >>> msle(y_true, y_pred).numpy()\n 0.480\n\n >>> # Using 'none' reduction type.\n >>> msle = tf.keras.losses.MeanSquaredLogarithmicError(\n ... reduction=tf.keras.losses.Reduction.NONE)\n >>> msle(y_true, y_pred).numpy()\n array([0.240, 0.240], dtype=float32)\n\n Usage with the `compile()` API:\n\n ```python\n model.compile(optimizer='sgd',\n loss=tf.keras.losses.MeanSquaredLogarithmicError())\n ```\n \"\"\"\n\n def __init__(self,\n reduction=losses_utils.ReductionV2.AUTO,\n name='mean_squared_logarithmic_error'):\n \"\"\"Initializes `MeanSquaredLogarithmicError` instance.\n\n Args:\n reduction: (Optional) Type of `tf.keras.losses.Reduction` to apply to\n loss. Default value is `AUTO`. `AUTO` indicates that the reduction\n option will be determined by the usage context. For almost all cases\n this defaults to `SUM_OVER_BATCH_SIZE`. When used with\n `tf.distribute.Strategy`, outside of built-in training loops such as\n `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`\n will raise an error. Please see this custom training [tutorial](\n https://www.tensorflow.org/tutorials/distribute/custom_training)\n for more details.\n name: Optional name for the op. Defaults to\n 'mean_squared_logarithmic_error'.\n \"\"\"\n super(MeanSquaredLogarithmicError, self).__init__(\n mean_squared_logarithmic_error, name=name, reduction=reduction)\n\n\n@keras_export('keras.losses.BinaryCrossentropy')\nclass BinaryCrossentropy(LossFunctionWrapper):\n \"\"\"Computes the cross-entropy loss between true labels and predicted labels.\n\n Use this cross-entropy loss when there are only two label classes (assumed to\n be 0 and 1). For each example, there should be a single floating-point value\n per prediction.\n\n In the snippet below, each of the four examples has only a single\n floating-pointing value, and both `y_pred` and `y_true` have the shape\n `[batch_size]`.\n\n Standalone usage:\n\n >>> y_true = [[0., 1.], [0., 0.]]\n >>> y_pred = [[0.6, 0.4], [0.4, 0.6]]\n >>> # Using 'auto'/'sum_over_batch_size' reduction type.\n >>> bce = tf.keras.losses.BinaryCrossentropy()\n >>> bce(y_true, y_pred).numpy()\n 0.815\n\n >>> # Calling with 'sample_weight'.\n >>> bce(y_true, y_pred, sample_weight=[1, 0]).numpy()\n 0.458\n\n >>> # Using 'sum' reduction type.\n >>> bce = tf.keras.losses.BinaryCrossentropy(\n ... reduction=tf.keras.losses.Reduction.SUM)\n >>> bce(y_true, y_pred).numpy()\n 1.630\n\n >>> # Using 'none' reduction type.\n >>> bce = tf.keras.losses.BinaryCrossentropy(\n ... reduction=tf.keras.losses.Reduction.NONE)\n >>> bce(y_true, y_pred).numpy()\n array([0.916 , 0.714], dtype=float32)\n\n Usage with the `tf.keras` API:\n\n ```python\n model.compile(optimizer='sgd', loss=tf.keras.losses.BinaryCrossentropy())\n ```\n \"\"\"\n\n def __init__(self,\n from_logits=False,\n label_smoothing=0,\n reduction=losses_utils.ReductionV2.AUTO,\n name='binary_crossentropy'):\n \"\"\"Initializes `BinaryCrossentropy` instance.\n\n Args:\n from_logits: Whether to interpret `y_pred` as a tensor of\n [logit](https://en.wikipedia.org/wiki/Logit) values. By default, we\n assume that `y_pred` contains probabilities (i.e., values in [0, 1]).\n **Note - Using from_logits=True may be more numerically stable.\n label_smoothing: Float in [0, 1]. When 0, no smoothing occurs. When > 0,\n we compute the loss between the predicted labels and a smoothed version\n of the true labels, where the smoothing squeezes the labels towards 0.5.\n Larger values of `label_smoothing` correspond to heavier smoothing.\n reduction: (Optional) Type of `tf.keras.losses.Reduction` to apply to\n loss. Default value is `AUTO`. `AUTO` indicates that the reduction\n option will be determined by the usage context. For almost all cases\n this defaults to `SUM_OVER_BATCH_SIZE`. When used with\n `tf.distribute.Strategy`, outside of built-in training loops such as\n `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`\n will raise an error. Please see this custom training [tutorial](\n https://www.tensorflow.org/tutorials/distribute/custom_training)\n for more details.\n name: (Optional) Name for the op. Defaults to 'binary_crossentropy'.\n \"\"\"\n super(BinaryCrossentropy, self).__init__(\n binary_crossentropy,\n name=name,\n reduction=reduction,\n from_logits=from_logits,\n label_smoothing=label_smoothing)\n self.from_logits = from_logits\n\n\n@keras_export('keras.losses.CategoricalCrossentropy')\nclass CategoricalCrossentropy(LossFunctionWrapper):\n \"\"\"Computes the crossentropy loss between the labels and predictions.\n\n Use this crossentropy loss function when there are two or more label classes.\n We expect labels to be provided in a `one_hot` representation. If you want to\n provide labels as integers, please use `SparseCategoricalCrossentropy` loss.\n There should be `# classes` floating point values per feature.\n\n In the snippet below, there is `# classes` floating pointing values per\n example. The shape of both `y_pred` and `y_true` are\n `[batch_size, num_classes]`.\n\n Standalone usage:\n\n >>> y_true = [[0, 1, 0], [0, 0, 1]]\n >>> y_pred = [[0.05, 0.95, 0], [0.1, 0.8, 0.1]]\n >>> # Using 'auto'/'sum_over_batch_size' reduction type.\n >>> cce = tf.keras.losses.CategoricalCrossentropy()\n >>> cce(y_true, y_pred).numpy()\n 1.177\n\n >>> # Calling with 'sample_weight'.\n >>> cce(y_true, y_pred, sample_weight=tf.constant([0.3, 0.7])).numpy()\n 0.814\n\n >>> # Using 'sum' reduction type.\n >>> cce = tf.keras.losses.CategoricalCrossentropy(\n ... reduction=tf.keras.losses.Reduction.SUM)\n >>> cce(y_true, y_pred).numpy()\n 2.354\n\n >>> # Using 'none' reduction type.\n >>> cce = tf.keras.losses.CategoricalCrossentropy(\n ... reduction=tf.keras.losses.Reduction.NONE)\n >>> cce(y_true, y_pred).numpy()\n array([0.0513, 2.303], dtype=float32)\n\n Usage with the `compile()` API:\n\n ```python\n model.compile(optimizer='sgd', loss=tf.keras.losses.CategoricalCrossentropy())\n ```\n \"\"\"\n\n def __init__(self,\n from_logits=False,\n label_smoothing=0,\n reduction=losses_utils.ReductionV2.AUTO,\n name='categorical_crossentropy'):\n \"\"\"Initializes `CategoricalCrossentropy` instance.\n\n Args:\n from_logits: Whether `y_pred` is expected to be a logits tensor. By\n default, we assume that `y_pred` encodes a probability distribution.\n **Note - Using from_logits=True is more numerically stable.**\n label_smoothing: Float in [0, 1]. When > 0, label values are smoothed,\n meaning the confidence on label values are relaxed. e.g.\n `label_smoothing=0.2` means that we will use a value of `0.1` for label\n `0` and `0.9` for label `1`\"\n reduction: (Optional) Type of `tf.keras.losses.Reduction` to apply to\n loss. Default value is `AUTO`. `AUTO` indicates that the reduction\n option will be determined by the usage context. For almost all cases\n this defaults to `SUM_OVER_BATCH_SIZE`. When used with\n `tf.distribute.Strategy`, outside of built-in training loops such as\n `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`\n will raise an error. Please see this custom training [tutorial](\n https://www.tensorflow.org/tutorials/distribute/custom_training)\n for more details.\n name: Optional name for the op. Defaults to 'categorical_crossentropy'.\n \"\"\"\n super(CategoricalCrossentropy, self).__init__(\n categorical_crossentropy,\n name=name,\n reduction=reduction,\n from_logits=from_logits,\n label_smoothing=label_smoothing)\n\n\n@keras_export('keras.losses.SparseCategoricalCrossentropy')\nclass SparseCategoricalCrossentropy(LossFunctionWrapper):\n \"\"\"Computes the crossentropy loss between the labels and predictions.\n\n Use this crossentropy loss function when there are two or more label classes.\n We expect labels to be provided as integers. If you want to provide labels\n using `one-hot` representation, please use `CategoricalCrossentropy` loss.\n There should be `# classes` floating point values per feature for `y_pred`\n and a single floating point value per feature for `y_true`.\n\n In the snippet below, there is a single floating point value per example for\n `y_true` and `# classes` floating pointing values per example for `y_pred`.\n The shape of `y_true` is `[batch_size]` and the shape of `y_pred` is\n `[batch_size, num_classes]`.\n\n Standalone usage:\n\n >>> y_true = [1, 2]\n >>> y_pred = [[0.05, 0.95, 0], [0.1, 0.8, 0.1]]\n >>> # Using 'auto'/'sum_over_batch_size' reduction type.\n >>> scce = tf.keras.losses.SparseCategoricalCrossentropy()\n >>> scce(y_true, y_pred).numpy()\n 1.177\n\n >>> # Calling with 'sample_weight'.\n >>> scce(y_true, y_pred, sample_weight=tf.constant([0.3, 0.7])).numpy()\n 0.814\n\n >>> # Using 'sum' reduction type.\n >>> scce = tf.keras.losses.SparseCategoricalCrossentropy(\n ... reduction=tf.keras.losses.Reduction.SUM)\n >>> scce(y_true, y_pred).numpy()\n 2.354\n\n >>> # Using 'none' reduction type.\n >>> scce = tf.keras.losses.SparseCategoricalCrossentropy(\n ... reduction=tf.keras.losses.Reduction.NONE)\n >>> scce(y_true, y_pred).numpy()\n array([0.0513, 2.303], dtype=float32)\n\n Usage with the `compile()` API:\n\n ```python\n model.compile(optimizer='sgd',\n loss=tf.keras.losses.SparseCategoricalCrossentropy())\n ```\n \"\"\"\n\n def __init__(self,\n from_logits=False,\n reduction=losses_utils.ReductionV2.AUTO,\n name='sparse_categorical_crossentropy'):\n \"\"\"Initializes `SparseCategoricalCrossentropy` instance.\n\n Args:\n from_logits: Whether `y_pred` is expected to be a logits tensor. By\n default, we assume that `y_pred` encodes a probability distribution.\n **Note - Using from_logits=True may be more numerically stable.\n reduction: (Optional) Type of `tf.keras.losses.Reduction` to apply to\n loss. Default value is `AUTO`. `AUTO` indicates that the reduction\n option will be determined by the usage context. For almost all cases\n this defaults to `SUM_OVER_BATCH_SIZE`. When used with\n `tf.distribute.Strategy`, outside of built-in training loops such as\n `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`\n will raise an error. Please see this custom training [tutorial](\n https://www.tensorflow.org/tutorials/distribute/custom_training)\n for more details.\n name: Optional name for the op. Defaults to\n 'sparse_categorical_crossentropy'.\n \"\"\"\n super(SparseCategoricalCrossentropy, self).__init__(\n sparse_categorical_crossentropy,\n name=name,\n reduction=reduction,\n from_logits=from_logits)\n\n\n@keras_export('keras.losses.Hinge')\nclass Hinge(LossFunctionWrapper):\n \"\"\"Computes the hinge loss between `y_true` and `y_pred`.\n\n `loss = maximum(1 - y_true * y_pred, 0)`\n\n `y_true` values are expected to be -1 or 1. If binary (0 or 1) labels are\n provided we will convert them to -1 or 1.\n\n Standalone usage:\n\n >>> y_true = [[0., 1.], [0., 0.]]\n >>> y_pred = [[0.6, 0.4], [0.4, 0.6]]\n >>> # Using 'auto'/'sum_over_batch_size' reduction type.\n >>> h = tf.keras.losses.Hinge()\n >>> h(y_true, y_pred).numpy()\n 1.3\n\n >>> # Calling with 'sample_weight'.\n >>> h(y_true, y_pred, sample_weight=[1, 0]).numpy()\n 0.55\n\n >>> # Using 'sum' reduction type.\n >>> h = tf.keras.losses.Hinge(\n ... reduction=tf.keras.losses.Reduction.SUM)\n >>> h(y_true, y_pred).numpy()\n 2.6\n\n >>> # Using 'none' reduction type.\n >>> h = tf.keras.losses.Hinge(\n ... reduction=tf.keras.losses.Reduction.NONE)\n >>> h(y_true, y_pred).numpy()\n array([1.1, 1.5], dtype=float32)\n\n Usage with the `compile()` API:\n\n ```python\n model.compile(optimizer='sgd', loss=tf.keras.losses.Hinge())\n ```\n \"\"\"\n\n def __init__(self, reduction=losses_utils.ReductionV2.AUTO, name='hinge'):\n \"\"\"Initializes `Hinge` instance.\n\n Args:\n reduction: (Optional) Type of `tf.keras.losses.Reduction` to apply to\n loss. Default value is `AUTO`. `AUTO` indicates that the reduction\n option will be determined by the usage context. For almost all cases\n this defaults to `SUM_OVER_BATCH_SIZE`. When used with\n `tf.distribute.Strategy`, outside of built-in training loops such as\n `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`\n will raise an error. Please see this custom training [tutorial](\n https://www.tensorflow.org/tutorials/distribute/custom_training)\n for more details.\n name: Optional name for the op. Defaults to 'hinge'.\n \"\"\"\n super(Hinge, self).__init__(hinge, name=name, reduction=reduction)\n\n\n@keras_export('keras.losses.SquaredHinge')\nclass SquaredHinge(LossFunctionWrapper):\n \"\"\"Computes the squared hinge loss between `y_true` and `y_pred`.\n\n `loss = square(maximum(1 - y_true * y_pred, 0))`\n\n `y_true` values are expected to be -1 or 1. If binary (0 or 1) labels are\n provided we will convert them to -1 or 1.\n\n Standalone usage:\n\n >>> y_true = [[0., 1.], [0., 0.]]\n >>> y_pred = [[0.6, 0.4], [0.4, 0.6]]\n >>> # Using 'auto'/'sum_over_batch_size' reduction type.\n >>> h = tf.keras.losses.SquaredHinge()\n >>> h(y_true, y_pred).numpy()\n 1.86\n\n >>> # Calling with 'sample_weight'.\n >>> h(y_true, y_pred, sample_weight=[1, 0]).numpy()\n 0.73\n\n >>> # Using 'sum' reduction type.\n >>> h = tf.keras.losses.SquaredHinge(\n ... reduction=tf.keras.losses.Reduction.SUM)\n >>> h(y_true, y_pred).numpy()\n 3.72\n\n >>> # Using 'none' reduction type.\n >>> h = tf.keras.losses.SquaredHinge(\n ... reduction=tf.keras.losses.Reduction.NONE)\n >>> h(y_true, y_pred).numpy()\n array([1.46, 2.26], dtype=float32)\n\n Usage with the `compile()` API:\n\n ```python\n model.compile(optimizer='sgd', loss=tf.keras.losses.SquaredHinge())\n ```\n \"\"\"\n\n def __init__(self,\n reduction=losses_utils.ReductionV2.AUTO,\n name='squared_hinge'):\n \"\"\"Initializes `SquaredHinge` instance.\n\n Args:\n reduction: (Optional) Type of `tf.keras.losses.Reduction` to apply to\n loss. Default value is `AUTO`. `AUTO` indicates that the reduction\n option will be determined by the usage context. For almost all cases\n this defaults to `SUM_OVER_BATCH_SIZE`. When used with\n `tf.distribute.Strategy`, outside of built-in training loops such as\n `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`\n will raise an error. Please see this custom training [tutorial](\n https://www.tensorflow.org/tutorials/distribute/custom_training)\n for more details.\n name: Optional name for the op. Defaults to 'squared_hinge'.\n \"\"\"\n super(SquaredHinge, self).__init__(\n squared_hinge, name=name, reduction=reduction)\n\n\n@keras_export('keras.losses.CategoricalHinge')\nclass CategoricalHinge(LossFunctionWrapper):\n \"\"\"Computes the categorical hinge loss between `y_true` and `y_pred`.\n\n `loss = maximum(neg - pos + 1, 0)`\n where `neg=maximum((1-y_true)*y_pred) and pos=sum(y_true*y_pred)`\n\n Standalone usage:\n\n >>> y_true = [[0, 1], [0, 0]]\n >>> y_pred = [[0.6, 0.4], [0.4, 0.6]]\n >>> # Using 'auto'/'sum_over_batch_size' reduction type.\n >>> h = tf.keras.losses.CategoricalHinge()\n >>> h(y_true, y_pred).numpy()\n 1.4\n\n >>> # Calling with 'sample_weight'.\n >>> h(y_true, y_pred, sample_weight=[1, 0]).numpy()\n 0.6\n\n >>> # Using 'sum' reduction type.\n >>> h = tf.keras.losses.CategoricalHinge(\n ... reduction=tf.keras.losses.Reduction.SUM)\n >>> h(y_true, y_pred).numpy()\n 2.8\n\n >>> # Using 'none' reduction type.\n >>> h = tf.keras.losses.CategoricalHinge(\n ... reduction=tf.keras.losses.Reduction.NONE)\n >>> h(y_true, y_pred).numpy()\n array([1.2, 1.6], dtype=float32)\n\n Usage with the `compile()` API:\n\n ```python\n model.compile(optimizer='sgd', loss=tf.keras.losses.CategoricalHinge())\n ```\n \"\"\"\n\n def __init__(self,\n reduction=losses_utils.ReductionV2.AUTO,\n name='categorical_hinge'):\n \"\"\"Initializes `CategoricalHinge` instance.\n\n Args:\n reduction: (Optional) Type of `tf.keras.losses.Reduction` to apply to\n loss. Default value is `AUTO`. `AUTO` indicates that the reduction\n option will be determined by the usage context. For almost all cases\n this defaults to `SUM_OVER_BATCH_SIZE`. When used with\n `tf.distribute.Strategy`, outside of built-in training loops such as\n `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`\n will raise an error. Please see this custom training [tutorial](\n https://www.tensorflow.org/tutorials/distribute/custom_training)\n for more details.\n name: Optional name for the op. Defaults to 'categorical_hinge'.\n \"\"\"\n super(CategoricalHinge, self).__init__(\n categorical_hinge, name=name, reduction=reduction)\n\n\n@keras_export('keras.losses.Poisson')\nclass Poisson(LossFunctionWrapper):\n \"\"\"Computes the Poisson loss between `y_true` and `y_pred`.\n\n `loss = y_pred - y_true * log(y_pred)`\n\n Standalone usage:\n\n >>> y_true = [[0., 1.], [0., 0.]]\n >>> y_pred = [[1., 1.], [0., 0.]]\n >>> # Using 'auto'/'sum_over_batch_size' reduction type.\n >>> p = tf.keras.losses.Poisson()\n >>> p(y_true, y_pred).numpy()\n 0.5\n\n >>> # Calling with 'sample_weight'.\n >>> p(y_true, y_pred, sample_weight=[0.8, 0.2]).numpy()\n 0.4\n\n >>> # Using 'sum' reduction type.\n >>> p = tf.keras.losses.Poisson(\n ... reduction=tf.keras.losses.Reduction.SUM)\n >>> p(y_true, y_pred).numpy()\n 0.999\n\n >>> # Using 'none' reduction type.\n >>> p = tf.keras.losses.Poisson(\n ... reduction=tf.keras.losses.Reduction.NONE)\n >>> p(y_true, y_pred).numpy()\n array([0.999, 0.], dtype=float32)\n\n Usage with the `compile()` API:\n\n ```python\n model.compile(optimizer='sgd', loss=tf.keras.losses.Poisson())\n ```\n \"\"\"\n\n def __init__(self, reduction=losses_utils.ReductionV2.AUTO, name='poisson'):\n \"\"\"Initializes `Poisson` instance.\n\n Args:\n reduction: (Optional) Type of `tf.keras.losses.Reduction` to apply to\n loss. Default value is `AUTO`. `AUTO` indicates that the reduction\n option will be determined by the usage context. For almost all cases\n this defaults to `SUM_OVER_BATCH_SIZE`. When used with\n `tf.distribute.Strategy`, outside of built-in training loops such as\n `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`\n will raise an error. Please see this custom training [tutorial](\n https://www.tensorflow.org/tutorials/distribute/custom_training)\n for more details.\n name: Optional name for the op. Defaults to 'poisson'.\n \"\"\"\n super(Poisson, self).__init__(poisson, name=name, reduction=reduction)\n\n\n@keras_export('keras.losses.LogCosh')\nclass LogCosh(LossFunctionWrapper):\n \"\"\"Computes the logarithm of the hyperbolic cosine of the prediction error.\n\n `logcosh = log((exp(x) + exp(-x))/2)`,\n where x is the error `y_pred - y_true`.\n\n Standalone usage:\n\n >>> y_true = [[0., 1.], [0., 0.]]\n >>> y_pred = [[1., 1.], [0., 0.]]\n >>> # Using 'auto'/'sum_over_batch_size' reduction type.\n >>> l = tf.keras.losses.LogCosh()\n >>> l(y_true, y_pred).numpy()\n 0.108\n\n >>> # Calling with 'sample_weight'.\n >>> l(y_true, y_pred, sample_weight=[0.8, 0.2]).numpy()\n 0.087\n\n >>> # Using 'sum' reduction type.\n >>> l = tf.keras.losses.LogCosh(\n ... reduction=tf.keras.losses.Reduction.SUM)\n >>> l(y_true, y_pred).numpy()\n 0.217\n\n >>> # Using 'none' reduction type.\n >>> l = tf.keras.losses.LogCosh(\n ... reduction=tf.keras.losses.Reduction.NONE)\n >>> l(y_true, y_pred).numpy()\n array([0.217, 0.], dtype=float32)\n\n Usage with the `compile()` API:\n\n ```python\n model.compile(optimizer='sgd', loss=tf.keras.losses.LogCosh())\n ```\n \"\"\"\n\n def __init__(self, reduction=losses_utils.ReductionV2.AUTO, name='log_cosh'):\n \"\"\"Initializes `LogCosh` instance.\n\n Args:\n reduction: (Optional) Type of `tf.keras.losses.Reduction` to apply to\n loss. Default value is `AUTO`. `AUTO` indicates that the reduction\n option will be determined by the usage context. For almost all cases\n this defaults to `SUM_OVER_BATCH_SIZE`. When used with\n `tf.distribute.Strategy`, outside of built-in training loops such as\n `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`\n will raise an error. Please see this custom training [tutorial](\n https://www.tensorflow.org/tutorials/distribute/custom_training)\n for more details.\n name: Optional name for the op. Defaults to 'log_cosh'.\n \"\"\"\n super(LogCosh, self).__init__(log_cosh, name=name, reduction=reduction)\n\n\n@keras_export('keras.losses.KLDivergence')\nclass KLDivergence(LossFunctionWrapper):\n \"\"\"Computes Kullback-Leibler divergence loss between `y_true` and `y_pred`.\n\n `loss = y_true * log(y_true / y_pred)`\n\n See: https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence\n\n Standalone usage:\n\n >>> y_true = [[0, 1], [0, 0]]\n >>> y_pred = [[0.6, 0.4], [0.4, 0.6]]\n >>> # Using 'auto'/'sum_over_batch_size' reduction type.\n >>> kl = tf.keras.losses.KLDivergence()\n >>> kl(y_true, y_pred).numpy()\n 0.458\n\n >>> # Calling with 'sample_weight'.\n >>> kl(y_true, y_pred, sample_weight=[0.8, 0.2]).numpy()\n 0.366\n\n >>> # Using 'sum' reduction type.\n >>> kl = tf.keras.losses.KLDivergence(\n ... reduction=tf.keras.losses.Reduction.SUM)\n >>> kl(y_true, y_pred).numpy()\n 0.916\n\n >>> # Using 'none' reduction type.\n >>> kl = tf.keras.losses.KLDivergence(\n ... reduction=tf.keras.losses.Reduction.NONE)\n >>> kl(y_true, y_pred).numpy()\n array([0.916, -3.08e-06], dtype=float32)\n\n Usage with the `compile()` API:\n\n ```python\n model.compile(optimizer='sgd', loss=tf.keras.losses.KLDivergence())\n ```\n \"\"\"\n\n def __init__(self,\n reduction=losses_utils.ReductionV2.AUTO,\n name='kl_divergence'):\n \"\"\"Initializes `KLDivergence` instance.\n\n Args:\n reduction: (Optional) Type of `tf.keras.losses.Reduction` to apply to\n loss. Default value is `AUTO`. `AUTO` indicates that the reduction\n option will be determined by the usage context. For almost all cases\n this defaults to `SUM_OVER_BATCH_SIZE`. When used with\n `tf.distribute.Strategy`, outside of built-in training loops such as\n `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`\n will raise an error. Please see this custom training [tutorial](\n https://www.tensorflow.org/tutorials/distribute/custom_training)\n for more details.\n name: Optional name for the op. Defaults to 'kl_divergence'.\n \"\"\"\n super(KLDivergence, self).__init__(\n kl_divergence, name=name, reduction=reduction)\n\n\n@keras_export('keras.losses.Huber')\nclass Huber(LossFunctionWrapper):\n \"\"\"Computes the Huber loss between `y_true` and `y_pred`.\n\n For each value x in `error = y_true - y_pred`:\n\n ```\n loss = 0.5 * x^2 if |x| <= d\n loss = 0.5 * d^2 + d * (|x| - d) if |x| > d\n ```\n where d is `delta`. See: https://en.wikipedia.org/wiki/Huber_loss\n\n Standalone usage:\n\n >>> y_true = [[0, 1], [0, 0]]\n >>> y_pred = [[0.6, 0.4], [0.4, 0.6]]\n >>> # Using 'auto'/'sum_over_batch_size' reduction type.\n >>> h = tf.keras.losses.Huber()\n >>> h(y_true, y_pred).numpy()\n 0.155\n\n >>> # Calling with 'sample_weight'.\n >>> h(y_true, y_pred, sample_weight=[1, 0]).numpy()\n 0.09\n\n >>> # Using 'sum' reduction type.\n >>> h = tf.keras.losses.Huber(\n ... reduction=tf.keras.losses.Reduction.SUM)\n >>> h(y_true, y_pred).numpy()\n 0.31\n\n >>> # Using 'none' reduction type.\n >>> h = tf.keras.losses.Huber(\n ... reduction=tf.keras.losses.Reduction.NONE)\n >>> h(y_true, y_pred).numpy()\n array([0.18, 0.13], dtype=float32)\n\n Usage with the `compile()` API:\n\n ```python\n model.compile(optimizer='sgd', loss=tf.keras.losses.Huber())\n ```\n \"\"\"\n\n def __init__(self,\n delta=1.0,\n reduction=losses_utils.ReductionV2.AUTO,\n name='huber_loss'):\n \"\"\"Initializes `Huber` instance.\n\n Args:\n delta: A float, the point where the Huber loss function changes from a\n quadratic to linear.\n reduction: (Optional) Type of `tf.keras.losses.Reduction` to apply to\n loss. Default value is `AUTO`. `AUTO` indicates that the reduction\n option will be determined by the usage context. For almost all cases\n this defaults to `SUM_OVER_BATCH_SIZE`. When used with\n `tf.distribute.Strategy`, outside of built-in training loops such as\n `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`\n will raise an error. Please see this custom training [tutorial](\n https://www.tensorflow.org/tutorials/distribute/custom_training)\n for more details.\n name: Optional name for the op. Defaults to 'huber_loss'.\n \"\"\"\n super(Huber, self).__init__(\n huber, name=name, reduction=reduction, delta=delta)\n\n\n@keras_export('keras.metrics.mean_squared_error',\n 'keras.metrics.mse',\n 'keras.metrics.MSE',\n 'keras.losses.mean_squared_error',\n 'keras.losses.mse',\n 'keras.losses.MSE')\[email protected]_dispatch_support\ndef mean_squared_error(y_true, y_pred):\n \"\"\"Computes the mean squared error between labels and predictions.\n\n After computing the squared distance between the inputs, the mean value over\n the last dimension is returned.\n\n `loss = mean(square(y_true - y_pred), axis=-1)`\n\n Standalone usage:\n\n >>> y_true = np.random.randint(0, 2, size=(2, 3))\n >>> y_pred = np.random.random(size=(2, 3))\n >>> loss = tf.keras.losses.mean_squared_error(y_true, y_pred)\n >>> assert loss.shape == (2,)\n >>> assert np.array_equal(\n ... loss.numpy(), np.mean(np.square(y_true - y_pred), axis=-1))\n\n Args:\n y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`.\n y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`.\n\n Returns:\n Mean squared error values. shape = `[batch_size, d0, .. dN-1]`.\n \"\"\"\n y_pred = ops.convert_to_tensor_v2(y_pred)\n y_true = math_ops.cast(y_true, y_pred.dtype)\n return K.mean(math_ops.squared_difference(y_pred, y_true), axis=-1)\n\n\n@keras_export('keras.metrics.mean_absolute_error',\n 'keras.metrics.mae',\n 'keras.metrics.MAE',\n 'keras.losses.mean_absolute_error',\n 'keras.losses.mae',\n 'keras.losses.MAE')\[email protected]_dispatch_support\ndef mean_absolute_error(y_true, y_pred):\n \"\"\"Computes the mean absolute error between labels and predictions.\n\n `loss = mean(abs(y_true - y_pred), axis=-1)`\n\n Standalone usage:\n\n >>> y_true = np.random.randint(0, 2, size=(2, 3))\n >>> y_pred = np.random.random(size=(2, 3))\n >>> loss = tf.keras.losses.mean_absolute_error(y_true, y_pred)\n >>> assert loss.shape == (2,)\n >>> assert np.array_equal(\n ... loss.numpy(), np.mean(np.abs(y_true - y_pred), axis=-1))\n\n Args:\n y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`.\n y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`.\n\n Returns:\n Mean absolute error values. shape = `[batch_size, d0, .. dN-1]`.\n \"\"\"\n y_pred = ops.convert_to_tensor_v2(y_pred)\n y_true = math_ops.cast(y_true, y_pred.dtype)\n return K.mean(math_ops.abs(y_pred - y_true), axis=-1)\n\n\n@keras_export('keras.metrics.mean_absolute_percentage_error',\n 'keras.metrics.mape',\n 'keras.metrics.MAPE',\n 'keras.losses.mean_absolute_percentage_error',\n 'keras.losses.mape',\n 'keras.losses.MAPE')\[email protected]_dispatch_support\ndef mean_absolute_percentage_error(y_true, y_pred):\n \"\"\"Computes the mean absolute percentage error between `y_true` and `y_pred`.\n\n `loss = 100 * mean(abs((y_true - y_pred) / y_true), axis=-1)`\n\n Standalone usage:\n\n >>> y_true = np.random.random(size=(2, 3))\n >>> y_true = np.maximum(y_true, 1e-7) # Prevent division by zero\n >>> y_pred = np.random.random(size=(2, 3))\n >>> loss = tf.keras.losses.mean_absolute_percentage_error(y_true, y_pred)\n >>> assert loss.shape == (2,)\n >>> assert np.array_equal(\n ... loss.numpy(),\n ... 100. * np.mean(np.abs((y_true - y_pred) / y_true), axis=-1))\n\n Args:\n y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`.\n y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`.\n\n Returns:\n Mean absolute percentage error values. shape = `[batch_size, d0, .. dN-1]`.\n \"\"\"\n y_pred = ops.convert_to_tensor_v2(y_pred)\n y_true = math_ops.cast(y_true, y_pred.dtype)\n diff = math_ops.abs(\n (y_true - y_pred) / K.maximum(math_ops.abs(y_true), K.epsilon()))\n return 100. * K.mean(diff, axis=-1)\n\n\n@keras_export('keras.metrics.mean_squared_logarithmic_error',\n 'keras.metrics.msle',\n 'keras.metrics.MSLE',\n 'keras.losses.mean_squared_logarithmic_error',\n 'keras.losses.msle',\n 'keras.losses.MSLE')\[email protected]_dispatch_support\ndef mean_squared_logarithmic_error(y_true, y_pred):\n \"\"\"Computes the mean squared logarithmic error between `y_true` and `y_pred`.\n\n `loss = mean(square(log(y_true + 1) - log(y_pred + 1)), axis=-1)`\n\n Standalone usage:\n\n >>> y_true = np.random.randint(0, 2, size=(2, 3))\n >>> y_pred = np.random.random(size=(2, 3))\n >>> loss = tf.keras.losses.mean_squared_logarithmic_error(y_true, y_pred)\n >>> assert loss.shape == (2,)\n >>> y_true = np.maximum(y_true, 1e-7)\n >>> y_pred = np.maximum(y_pred, 1e-7)\n >>> assert np.array_equal(\n ... loss.numpy(),\n ... np.mean(\n ... np.square(np.log(y_true + 1.) - np.log(y_pred + 1.)), axis=-1))\n\n Args:\n y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`.\n y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`.\n\n Returns:\n Mean squared logarithmic error values. shape = `[batch_size, d0, .. dN-1]`.\n \"\"\"\n y_pred = ops.convert_to_tensor_v2(y_pred)\n y_true = math_ops.cast(y_true, y_pred.dtype)\n first_log = math_ops.log(K.maximum(y_pred, K.epsilon()) + 1.)\n second_log = math_ops.log(K.maximum(y_true, K.epsilon()) + 1.)\n return K.mean(math_ops.squared_difference(first_log, second_log), axis=-1)\n\n\ndef _maybe_convert_labels(y_true):\n \"\"\"Converts binary labels into -1/1.\"\"\"\n are_zeros = math_ops.equal(y_true, 0)\n are_ones = math_ops.equal(y_true, 1)\n is_binary = math_ops.reduce_all(math_ops.logical_or(are_zeros, are_ones))\n\n def _convert_binary_labels():\n # Convert the binary labels to -1 or 1.\n return 2. * y_true - 1.\n\n updated_y_true = smart_cond.smart_cond(is_binary, _convert_binary_labels,\n lambda: y_true)\n return updated_y_true\n\n\n@keras_export('keras.metrics.squared_hinge', 'keras.losses.squared_hinge')\[email protected]_dispatch_support\ndef squared_hinge(y_true, y_pred):\n \"\"\"Computes the squared hinge loss between `y_true` and `y_pred`.\n\n `loss = mean(square(maximum(1 - y_true * y_pred, 0)), axis=-1)`\n\n Standalone usage:\n\n >>> y_true = np.random.choice([-1, 1], size=(2, 3))\n >>> y_pred = np.random.random(size=(2, 3))\n >>> loss = tf.keras.losses.squared_hinge(y_true, y_pred)\n >>> assert loss.shape == (2,)\n >>> assert np.array_equal(\n ... loss.numpy(),\n ... np.mean(np.square(np.maximum(1. - y_true * y_pred, 0.)), axis=-1))\n\n Args:\n y_true: The ground truth values. `y_true` values are expected to be -1 or 1.\n If binary (0 or 1) labels are provided we will convert them to -1 or 1.\n shape = `[batch_size, d0, .. dN]`.\n y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`.\n\n Returns:\n Squared hinge loss values. shape = `[batch_size, d0, .. dN-1]`.\n \"\"\"\n y_pred = ops.convert_to_tensor_v2(y_pred)\n y_true = math_ops.cast(y_true, y_pred.dtype)\n y_true = _maybe_convert_labels(y_true)\n return K.mean(\n math_ops.square(math_ops.maximum(1. - y_true * y_pred, 0.)), axis=-1)\n\n\n@keras_export('keras.metrics.hinge', 'keras.losses.hinge')\[email protected]_dispatch_support\ndef hinge(y_true, y_pred):\n \"\"\"Computes the hinge loss between `y_true` and `y_pred`.\n\n `loss = mean(maximum(1 - y_true * y_pred, 0), axis=-1)`\n\n Standalone usage:\n\n >>> y_true = np.random.choice([-1, 1], size=(2, 3))\n >>> y_pred = np.random.random(size=(2, 3))\n >>> loss = tf.keras.losses.hinge(y_true, y_pred)\n >>> assert loss.shape == (2,)\n >>> assert np.array_equal(\n ... loss.numpy(),\n ... np.mean(np.maximum(1. - y_true * y_pred, 0.), axis=-1))\n\n Args:\n y_true: The ground truth values. `y_true` values are expected to be -1 or 1.\n If binary (0 or 1) labels are provided they will be converted to -1 or 1.\n shape = `[batch_size, d0, .. dN]`.\n y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`.\n\n Returns:\n Hinge loss values. shape = `[batch_size, d0, .. dN-1]`.\n \"\"\"\n y_pred = ops.convert_to_tensor_v2(y_pred)\n y_true = math_ops.cast(y_true, y_pred.dtype)\n y_true = _maybe_convert_labels(y_true)\n return K.mean(math_ops.maximum(1. - y_true * y_pred, 0.), axis=-1)\n\n\n@keras_export('keras.losses.categorical_hinge')\[email protected]_dispatch_support\ndef categorical_hinge(y_true, y_pred):\n \"\"\"Computes the categorical hinge loss between `y_true` and `y_pred`.\n\n `loss = maximum(neg - pos + 1, 0)`\n where `neg=maximum((1-y_true)*y_pred) and pos=sum(y_true*y_pred)`\n\n Standalone usage:\n\n >>> y_true = np.random.randint(0, 3, size=(2,))\n >>> y_true = tf.keras.utils.to_categorical(y_true, num_classes=3)\n >>> y_pred = np.random.random(size=(2, 3))\n >>> loss = tf.keras.losses.categorical_hinge(y_true, y_pred)\n >>> assert loss.shape == (2,)\n >>> pos = np.sum(y_true * y_pred, axis=-1)\n >>> neg = np.amax((1. - y_true) * y_pred, axis=-1)\n >>> assert np.array_equal(loss.numpy(), np.maximum(0., neg - pos + 1.))\n\n Args:\n y_true: The ground truth values. `y_true` values are expected to be 0 or 1.\n y_pred: The predicted values.\n\n Returns:\n Categorical hinge loss values.\n \"\"\"\n y_pred = ops.convert_to_tensor_v2(y_pred)\n y_true = math_ops.cast(y_true, y_pred.dtype)\n pos = math_ops.reduce_sum(y_true * y_pred, axis=-1)\n neg = math_ops.reduce_max((1. - y_true) * y_pred, axis=-1)\n zero = math_ops.cast(0., y_pred.dtype)\n return math_ops.maximum(neg - pos + 1., zero)\n\n\n@keras_export('keras.losses.huber', v1=[])\[email protected]_dispatch_support\ndef huber(y_true, y_pred, delta=1.0):\n \"\"\"Computes Huber loss value.\n\n For each value x in `error = y_true - y_pred`:\n\n ```\n loss = 0.5 * x^2 if |x| <= d\n loss = 0.5 * d^2 + d * (|x| - d) if |x| > d\n ```\n where d is `delta`. See: https://en.wikipedia.org/wiki/Huber_loss\n\n Args:\n y_true: tensor of true targets.\n y_pred: tensor of predicted targets.\n delta: A float, the point where the Huber loss function changes from a\n quadratic to linear.\n\n Returns:\n Tensor with one scalar loss entry per sample.\n \"\"\"\n y_pred = math_ops.cast(y_pred, dtype=K.floatx())\n y_true = math_ops.cast(y_true, dtype=K.floatx())\n delta = math_ops.cast(delta, dtype=K.floatx())\n error = math_ops.subtract(y_pred, y_true)\n abs_error = math_ops.abs(error)\n half = ops.convert_to_tensor_v2(0.5, dtype=abs_error.dtype)\n return K.mean(\n array_ops.where_v2(\n abs_error <= delta, half * math_ops.pow(error, 2),\n half * math_ops.pow(delta, 2) + delta * (abs_error - delta)),\n axis=-1)\n\n\n@keras_export('keras.losses.log_cosh', 'keras.losses.logcosh')\[email protected]_dispatch_support\ndef log_cosh(y_true, y_pred):\n \"\"\"Logarithm of the hyperbolic cosine of the prediction error.\n\n `log(cosh(x))` is approximately equal to `(x ** 2) / 2` for small `x` and\n to `abs(x) - log(2)` for large `x`. This means that 'logcosh' works mostly\n like the mean squared error, but will not be so strongly affected by the\n occasional wildly incorrect prediction.\n\n Standalone usage:\n\n >>> y_true = np.random.random(size=(2, 3))\n >>> y_pred = np.random.random(size=(2, 3))\n >>> loss = tf.keras.losses.logcosh(y_true, y_pred)\n >>> assert loss.shape == (2,)\n >>> x = y_pred - y_true\n >>> assert np.allclose(\n ... loss.numpy(),\n ... np.mean(x + np.log(np.exp(-2. * x) + 1.) - math_ops.log(2.), axis=-1),\n ... atol=1e-5)\n\n Args:\n y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`.\n y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`.\n\n Returns:\n Logcosh error values. shape = `[batch_size, d0, .. dN-1]`.\n \"\"\"\n y_pred = ops.convert_to_tensor_v2(y_pred)\n y_true = math_ops.cast(y_true, y_pred.dtype)\n\n def _logcosh(x):\n return x + nn.softplus(-2. * x) - math_ops.cast(math_ops.log(2.), x.dtype)\n\n return K.mean(_logcosh(y_pred - y_true), axis=-1)\n\n\n@keras_export('keras.metrics.categorical_crossentropy',\n 'keras.losses.categorical_crossentropy')\[email protected]_dispatch_support\ndef categorical_crossentropy(y_true,\n y_pred,\n from_logits=False,\n label_smoothing=0):\n \"\"\"Computes the categorical crossentropy loss.\n\n Standalone usage:\n\n >>> y_true = [[0, 1, 0], [0, 0, 1]]\n >>> y_pred = [[0.05, 0.95, 0], [0.1, 0.8, 0.1]]\n >>> loss = tf.keras.losses.categorical_crossentropy(y_true, y_pred)\n >>> assert loss.shape == (2,)\n >>> loss.numpy()\n array([0.0513, 2.303], dtype=float32)\n\n Args:\n y_true: Tensor of one-hot true targets.\n y_pred: Tensor of predicted targets.\n from_logits: Whether `y_pred` is expected to be a logits tensor. By default,\n we assume that `y_pred` encodes a probability distribution.\n label_smoothing: Float in [0, 1]. If > `0` then smooth the labels.\n\n Returns:\n Categorical crossentropy loss value.\n \"\"\"\n y_pred = ops.convert_to_tensor_v2(y_pred)\n y_true = math_ops.cast(y_true, y_pred.dtype)\n label_smoothing = ops.convert_to_tensor_v2(label_smoothing, dtype=K.floatx())\n\n def _smooth_labels():\n num_classes = math_ops.cast(array_ops.shape(y_true)[-1], y_pred.dtype)\n return y_true * (1.0 - label_smoothing) + (label_smoothing / num_classes)\n\n y_true = smart_cond.smart_cond(label_smoothing, _smooth_labels,\n lambda: y_true)\n return K.categorical_crossentropy(y_true, y_pred, from_logits=from_logits)\n\n\n@keras_export('keras.metrics.sparse_categorical_crossentropy',\n 'keras.losses.sparse_categorical_crossentropy')\[email protected]_dispatch_support\ndef sparse_categorical_crossentropy(y_true, y_pred, from_logits=False, axis=-1):\n \"\"\"Computes the sparse categorical crossentropy loss.\n\n Standalone usage:\n\n >>> y_true = [1, 2]\n >>> y_pred = [[0.05, 0.95, 0], [0.1, 0.8, 0.1]]\n >>> loss = tf.keras.losses.sparse_categorical_crossentropy(y_true, y_pred)\n >>> assert loss.shape == (2,)\n >>> loss.numpy()\n array([0.0513, 2.303], dtype=float32)\n\n Args:\n y_true: Ground truth values.\n y_pred: The predicted values.\n from_logits: Whether `y_pred` is expected to be a logits tensor. By default,\n we assume that `y_pred` encodes a probability distribution.\n axis: (Optional) Defaults to -1. The dimension along which the entropy is\n computed.\n\n Returns:\n Sparse categorical crossentropy loss value.\n \"\"\"\n y_pred = ops.convert_to_tensor_v2(y_pred)\n y_true = math_ops.cast(y_true, y_pred.dtype)\n return K.sparse_categorical_crossentropy(\n y_true, y_pred, from_logits=from_logits, axis=axis)\n\n\n@keras_export('keras.metrics.binary_crossentropy',\n 'keras.losses.binary_crossentropy')\[email protected]_dispatch_support\ndef binary_crossentropy(y_true, y_pred, from_logits=False, label_smoothing=0):\n \"\"\"Computes the binary crossentropy loss.\n\n Standalone usage:\n\n >>> y_true = [[0, 1], [0, 0]]\n >>> y_pred = [[0.6, 0.4], [0.4, 0.6]]\n >>> loss = tf.keras.losses.binary_crossentropy(y_true, y_pred)\n >>> assert loss.shape == (2,)\n >>> loss.numpy()\n array([0.916 , 0.714], dtype=float32)\n\n Args:\n y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`.\n y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`.\n from_logits: Whether `y_pred` is expected to be a logits tensor. By default,\n we assume that `y_pred` encodes a probability distribution.\n label_smoothing: Float in [0, 1]. If > `0` then smooth the labels.\n\n Returns:\n Binary crossentropy loss value. shape = `[batch_size, d0, .. dN-1]`.\n \"\"\"\n y_pred = ops.convert_to_tensor_v2(y_pred)\n y_true = math_ops.cast(y_true, y_pred.dtype)\n label_smoothing = ops.convert_to_tensor_v2(label_smoothing, dtype=K.floatx())\n\n def _smooth_labels():\n return y_true * (1.0 - label_smoothing) + 0.5 * label_smoothing\n\n y_true = smart_cond.smart_cond(label_smoothing, _smooth_labels,\n lambda: y_true)\n return K.mean(\n K.binary_crossentropy(y_true, y_pred, from_logits=from_logits), axis=-1)\n\n\n@keras_export('keras.metrics.kl_divergence',\n 'keras.metrics.kullback_leibler_divergence',\n 'keras.metrics.kld',\n 'keras.metrics.KLD',\n 'keras.losses.kl_divergence',\n 'keras.losses.kullback_leibler_divergence',\n 'keras.losses.kld',\n 'keras.losses.KLD')\[email protected]_dispatch_support\ndef kl_divergence(y_true, y_pred):\n \"\"\"Computes Kullback-Leibler divergence loss between `y_true` and `y_pred`.\n\n `loss = y_true * log(y_true / y_pred)`\n\n See: https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence\n\n Standalone usage:\n\n >>> y_true = np.random.randint(0, 2, size=(2, 3)).astype(np.float64)\n >>> y_pred = np.random.random(size=(2, 3))\n >>> loss = tf.keras.losses.kullback_leibler_divergence(y_true, y_pred)\n >>> assert loss.shape == (2,)\n >>> y_true = tf.keras.backend.clip(y_true, 1e-7, 1)\n >>> y_pred = tf.keras.backend.clip(y_pred, 1e-7, 1)\n >>> assert np.array_equal(\n ... loss.numpy(), np.sum(y_true * np.log(y_true / y_pred), axis=-1))\n\n Args:\n y_true: Tensor of true targets.\n y_pred: Tensor of predicted targets.\n\n Returns:\n A `Tensor` with loss.\n\n Raises:\n TypeError: If `y_true` cannot be cast to the `y_pred.dtype`.\n \"\"\"\n y_pred = ops.convert_to_tensor_v2(y_pred)\n y_true = math_ops.cast(y_true, y_pred.dtype)\n y_true = K.clip(y_true, K.epsilon(), 1)\n y_pred = K.clip(y_pred, K.epsilon(), 1)\n return math_ops.reduce_sum(y_true * math_ops.log(y_true / y_pred), axis=-1)\n\n\n@keras_export('keras.metrics.poisson', 'keras.losses.poisson')\[email protected]_dispatch_support\ndef poisson(y_true, y_pred):\n \"\"\"Computes the Poisson loss between y_true and y_pred.\n\n The Poisson loss is the mean of the elements of the `Tensor`\n `y_pred - y_true * log(y_pred)`.\n\n Standalone usage:\n\n >>> y_true = np.random.randint(0, 2, size=(2, 3))\n >>> y_pred = np.random.random(size=(2, 3))\n >>> loss = tf.keras.losses.poisson(y_true, y_pred)\n >>> assert loss.shape == (2,)\n >>> y_pred = y_pred + 1e-7\n >>> assert np.allclose(\n ... loss.numpy(), np.mean(y_pred - y_true * np.log(y_pred), axis=-1),\n ... atol=1e-5)\n\n Args:\n y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`.\n y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`.\n\n Returns:\n Poisson loss value. shape = `[batch_size, d0, .. dN-1]`.\n\n Raises:\n InvalidArgumentError: If `y_true` and `y_pred` have incompatible shapes.\n \"\"\"\n y_pred = ops.convert_to_tensor_v2(y_pred)\n y_true = math_ops.cast(y_true, y_pred.dtype)\n return K.mean(y_pred - y_true * math_ops.log(y_pred + K.epsilon()), axis=-1)\n\n\n@keras_export(\n 'keras.losses.cosine_similarity',\n v1=[\n 'keras.metrics.cosine_proximity',\n 'keras.metrics.cosine',\n 'keras.losses.cosine_proximity',\n 'keras.losses.cosine',\n 'keras.losses.cosine_similarity',\n ])\[email protected]_dispatch_support\ndef cosine_similarity(y_true, y_pred, axis=-1):\n \"\"\"Computes the cosine similarity between labels and predictions.\n\n Note that it is a number between -1 and 1. When it is a negative number\n between -1 and 0, 0 indicates orthogonality and values closer to -1\n indicate greater similarity. The values closer to 1 indicate greater\n dissimilarity. This makes it usable as a loss function in a setting\n where you try to maximize the proximity between predictions and\n targets. If either `y_true` or `y_pred` is a zero vector, cosine\n similarity will be 0 regardless of the proximity between predictions\n and targets.\n\n `loss = -sum(l2_norm(y_true) * l2_norm(y_pred))`\n\n Standalone usage:\n\n >>> y_true = [[0., 1.], [1., 1.], [1., 1.]]\n >>> y_pred = [[1., 0.], [1., 1.], [-1., -1.]]\n >>> loss = tf.keras.losses.cosine_similarity(y_true, y_pred, axis=1)\n >>> loss.numpy()\n array([-0., -0.999, 0.999], dtype=float32)\n\n Args:\n y_true: Tensor of true targets.\n y_pred: Tensor of predicted targets.\n axis: Axis along which to determine similarity.\n\n Returns:\n Cosine similarity tensor.\n \"\"\"\n y_true = nn.l2_normalize(y_true, axis=axis)\n y_pred = nn.l2_normalize(y_pred, axis=axis)\n return -math_ops.reduce_sum(y_true * y_pred, axis=axis)\n\n\n@keras_export('keras.losses.CosineSimilarity')\nclass CosineSimilarity(LossFunctionWrapper):\n \"\"\"Computes the cosine similarity between labels and predictions.\n\n Note that it is a negative quantity between -1 and 0, where 0 indicates\n orthogonality and values closer to -1 indicate greater similarity. This makes\n it usable as a loss function in a setting where you try to maximize the\n proximity between predictions and targets. If either `y_true` or `y_pred`\n is a zero vector, cosine similarity will be 0 regardless of the proximity\n between predictions and targets.\n\n `loss = -sum(l2_norm(y_true) * l2_norm(y_pred))`\n\n Standalone usage:\n\n >>> y_true = [[0., 1.], [1., 1.]]\n >>> y_pred = [[1., 0.], [1., 1.]]\n >>> # Using 'auto'/'sum_over_batch_size' reduction type.\n >>> cosine_loss = tf.keras.losses.CosineSimilarity(axis=1)\n >>> # l2_norm(y_true) = [[0., 1.], [1./1.414], 1./1.414]]]\n >>> # l2_norm(y_pred) = [[1., 0.], [1./1.414], 1./1.414]]]\n >>> # l2_norm(y_true) . l2_norm(y_pred) = [[0., 0.], [0.5, 0.5]]\n >>> # loss = mean(sum(l2_norm(y_true) . l2_norm(y_pred), axis=1))\n >>> # = -((0. + 0.) + (0.5 + 0.5)) / 2\n >>> cosine_loss(y_true, y_pred).numpy()\n -0.5\n\n >>> # Calling with 'sample_weight'.\n >>> cosine_loss(y_true, y_pred, sample_weight=[0.8, 0.2]).numpy()\n -0.0999\n\n >>> # Using 'sum' reduction type.\n >>> cosine_loss = tf.keras.losses.CosineSimilarity(axis=1,\n ... reduction=tf.keras.losses.Reduction.SUM)\n >>> cosine_loss(y_true, y_pred).numpy()\n -0.999\n\n >>> # Using 'none' reduction type.\n >>> cosine_loss = tf.keras.losses.CosineSimilarity(axis=1,\n ... reduction=tf.keras.losses.Reduction.NONE)\n >>> cosine_loss(y_true, y_pred).numpy()\n array([-0., -0.999], dtype=float32)\n\n Usage with the `compile()` API:\n\n ```python\n model.compile(optimizer='sgd', loss=tf.keras.losses.CosineSimilarity(axis=1))\n ```\n\n Args:\n axis: (Optional) Defaults to -1. The dimension along which the cosine\n similarity is computed.\n reduction: (Optional) Type of `tf.keras.losses.Reduction` to apply to loss.\n Default value is `AUTO`. `AUTO` indicates that the reduction option will\n be determined by the usage context. For almost all cases this defaults to\n `SUM_OVER_BATCH_SIZE`. When used with `tf.distribute.Strategy`, outside of\n built-in training loops such as `tf.keras` `compile` and `fit`, using\n `AUTO` or `SUM_OVER_BATCH_SIZE` will raise an error. Please see this\n custom training [tutorial]\n (https://www.tensorflow.org/tutorials/distribute/custom_training) for more\n details.\n name: Optional name for the op.\n \"\"\"\n\n def __init__(self,\n axis=-1,\n reduction=losses_utils.ReductionV2.AUTO,\n name='cosine_similarity'):\n super(CosineSimilarity, self).__init__(\n cosine_similarity, reduction=reduction, name=name, axis=axis)\n\n\n# Aliases.\n\nbce = BCE = binary_crossentropy\nmse = MSE = mean_squared_error\nmae = MAE = mean_absolute_error\nmape = MAPE = mean_absolute_percentage_error\nmsle = MSLE = mean_squared_logarithmic_error\nkld = KLD = kullback_leibler_divergence = kl_divergence\nlogcosh = log_cosh\nhuber_loss = huber\n\n\ndef is_categorical_crossentropy(loss):\n result = ((isinstance(loss, CategoricalCrossentropy) or\n (isinstance(loss, LossFunctionWrapper) and\n loss.fn == categorical_crossentropy) or\n (hasattr(loss, '__name__') and\n loss.__name__ == 'categorical_crossentropy') or\n (loss == 'categorical_crossentropy')))\n return result\n\n\n@keras_export('keras.losses.serialize')\ndef serialize(loss):\n \"\"\"Serializes loss function or `Loss` instance.\n\n Arguments:\n loss: A Keras `Loss` instance or a loss function.\n\n Returns:\n Loss configuration dictionary.\n \"\"\"\n return serialize_keras_object(loss)\n\n\n@keras_export('keras.losses.deserialize')\ndef deserialize(name, custom_objects=None):\n \"\"\"Deserializes a serialized loss class/function instance.\n\n Arguments:\n name: Loss configuration.\n custom_objects: Optional dictionary mapping names (strings) to custom\n objects (classes and functions) to be considered during deserialization.\n\n Returns:\n A Keras `Loss` instance or a loss function.\n \"\"\"\n return deserialize_keras_object(\n name,\n module_objects=globals(),\n custom_objects=custom_objects,\n printable_module_name='loss function')\n\n\n@keras_export('keras.losses.get')\ndef get(identifier):\n \"\"\"Retrieves a Keras loss as a `function`/`Loss` class instance.\n\n The `identifier` may be the string name of a loss function or `Loss` class.\n\n >>> loss = tf.keras.losses.get(\"categorical_crossentropy\")\n >>> type(loss)\n <class 'function'>\n >>> loss = tf.keras.losses.get(\"CategoricalCrossentropy\")\n >>> type(loss)\n <class '...tensorflow.python.keras.losses.CategoricalCrossentropy'>\n\n You can also specify `config` of the loss to this function by passing dict\n containing `class_name` and `config` as an identifier. Also note that the\n `class_name` must map to a `Loss` class\n\n >>> identifier = {\"class_name\": \"CategoricalCrossentropy\",\n ... \"config\": {\"from_logits\": True}}\n >>> loss = tf.keras.losses.get(identifier)\n >>> type(loss)\n <class '...tensorflow.python.keras.losses.CategoricalCrossentropy'>\n\n Arguments:\n identifier: A loss identifier. One of None or string name of a loss\n function/class or loss configuration dictionary or a loss function or a\n loss class instance\n\n Returns:\n A Keras loss as a `function`/ `Loss` class instance.\n\n Raises:\n ValueError: If `identifier` cannot be interpreted.\n \"\"\"\n if identifier is None:\n return None\n if isinstance(identifier, six.string_types):\n identifier = str(identifier)\n return deserialize(identifier)\n if isinstance(identifier, dict):\n return deserialize(identifier)\n elif callable(identifier):\n return identifier\n else:\n raise ValueError(\n 'Could not interpret loss function identifier: {}'.format(identifier))\n\n\nLABEL_DTYPES_FOR_LOSSES = {\n losses_impl.sparse_softmax_cross_entropy: 'int32',\n sparse_categorical_crossentropy: 'int32'\n}\n"
] | [
[
"tensorflow.python.ops.math_ops.equal",
"tensorflow.python.ops.math_ops.maximum",
"tensorflow.python.keras.backend.categorical_crossentropy",
"tensorflow.python.keras.utils.tf_utils.is_tensor_or_variable",
"tensorflow.python.ops.math_ops.pow",
"tensorflow.python.ops.math_ops.squared_difference",
"tensorflow.python.keras.utils.tf_utils.graph_context_for_symbolic_tensors",
"tensorflow.python.framework.smart_cond.smart_cond",
"tensorflow.python.keras.backend.epsilon",
"tensorflow.python.ops.nn.softplus",
"tensorflow.python.keras.backend.eval",
"tensorflow.python.autograph.core.ag_ctx.control_status_ctx",
"tensorflow.python.ops.nn.l2_normalize",
"tensorflow.python.distribute.distribution_strategy_context.has_strategy",
"tensorflow.python.keras.backend.name_scope",
"tensorflow.python.keras.utils.losses_utils.squeeze_or_expand_dimensions",
"tensorflow.python.framework.ops.convert_to_tensor_v2",
"tensorflow.python.ops.math_ops.reduce_sum",
"tensorflow.python.ops.array_ops.shape",
"tensorflow.python.keras.utils.generic_utils.serialize_keras_object",
"tensorflow.python.keras.backend.sparse_categorical_crossentropy",
"tensorflow.python.ops.math_ops.cast",
"tensorflow.python.ops.math_ops.logical_or",
"tensorflow.python.util.tf_export.keras_export",
"tensorflow.python.keras.backend.floatx",
"tensorflow.python.ops.math_ops.reduce_max",
"tensorflow.python.ops.math_ops.abs",
"tensorflow.python.ops.math_ops.subtract",
"tensorflow.python.ops.math_ops.log",
"tensorflow.python.keras.backend.mean",
"tensorflow.python.keras.utils.losses_utils.ReductionV2.validate",
"tensorflow.python.keras.backend.binary_crossentropy",
"tensorflow.python.framework.tensor_util.is_tensor"
]
] |
YongfengGao/CNN-T-DB | [
"11c67eb94b6db36217a837fedd27b393532dd09b"
] | [
"test.py"
] | [
"import os,glob\r\nimport sys\r\nimport argparse\r\nimport numpy as np\r\nfrom scipy.io import savemat,loadmat\r\nimport torch\r\nfrom torch.autograd import Variable\r\nimport struct\r\nfrom shutil import rmtree\r\nfrom matplotlib import pyplot as plt\r\nfrom numpy import *\r\n\r\n\r\ndef testing():\r\n\r\n recon = np.zeros((512,512))\r\n for part,weight in zip(['lung',],[0.045]):\r\n with open(\"./models/\"+part, 'rb') as f: #please specifiy the model name here \r\n Vanilla_3D = torch.load(f).cuda(0)\r\n Vanilla_3D.eval()\r\n \r\n # specifiy the location of input patches\r\n folder=glob.glob(\"D:\\\\*\"+\"\\\\*.mat\")\r\n\r\n\r\n for f in folder:\r\n #print(f)\r\n if 'full' in f:\r\n continue\r\n coord = f.split(\"\\\\\")[-1].split(\".\")[0].split(\"-\")\r\n tmp_data = loadmat(f)['a']\r\n # y = tmp_data[3:4,3:4].copy()\r\n \r\n tmp_data[3:4,3:4] = 0.0\r\n tmp_data = tmp_data.reshape(\r\n tmp_data.shape[0], tmp_data.shape[1], 1)\r\n\r\n np_arr_data = np.array([tmp_data])\r\n\r\n test_image = np_arr_data.astype(np.float32)\r\n #print(test_image.shape)\r\n test_image = np.transpose(test_image, (0, 3, 1, 2))\r\n test_image = torch.from_numpy(test_image)\r\n\r\n test_image = test_image.cuda(0)\r\n test_image = Variable(test_image)\r\n\r\n pred = Vanilla_3D(test_image) #mid,\r\n\r\n ps = pred.cpu().data.numpy()\r\n ps = np.squeeze(ps, (0, 1))\r\n\r\n a = int(coord[0])\r\n b = int(coord[1])\r\n\r\n #residual[a, b] = float(ps[3][3])\r\n recon[a, b] = float(ps)*weight\r\n recon = recon \r\n savemat('result.mat',mdict={'a':recon})\r\n \r\ndef main(): \r\n print(\"start testing......\")\r\n testing()\r\n\r\nif __name__ == '__main__':\r\n main()\r\n sys.stdout.write(\"Done\")\r\n\r\n\r\n\r\n"
] | [
[
"scipy.io.loadmat",
"numpy.transpose",
"torch.load",
"numpy.zeros",
"numpy.squeeze",
"torch.autograd.Variable",
"scipy.io.savemat",
"torch.from_numpy",
"numpy.array"
]
] |
iBobbyTS/OpenVideoEnhance | [
"64d12d7a4c344798e5d60eafd20f8f554f852e84"
] | [
"ove/algorithm/basicvsr/fix_model.py"
] | [
"import torch\nori = torch.load('/Users/ibobby/Dataset/model_weights/BasicVSR/v-bi.pth')\nori = ori['state_dict']\nnew = {}\nfor k in ori.keys():\n new[k.replace('generator.', '')] = ori[k]\n# Rename\nm = list()\nu = list()\n# PixelShufflePack\nm += [\"upsample1.main.0.weight\", \"upsample1.main.0.bias\", \"upsample2.main.0.weight\", \"upsample2.main.0.bias\"]\nu += [\"upsample1.upsample_conv.weight\", \"upsample1.upsample_conv.bias\", \"upsample2.upsample_conv.weight\", \"upsample2.upsample_conv.bias\"]\n# ResidualBlock\nm += [\"backward_resblocks.main.2.conv.0.weight\", \"backward_resblocks.main.2.conv.0.bias\", \"backward_resblocks.main.2.conv.2.weight\", \"backward_resblocks.main.2.conv.2.bias\", \"backward_resblocks.main.3.conv.0.weight\", \"backward_resblocks.main.3.conv.0.bias\", \"backward_resblocks.main.3.conv.2.weight\", \"backward_resblocks.main.3.conv.2.bias\", \"backward_resblocks.main.4.conv.0.weight\", \"backward_resblocks.main.4.conv.0.bias\", \"backward_resblocks.main.4.conv.2.weight\", \"backward_resblocks.main.4.conv.2.bias\", \"backward_resblocks.main.5.conv.0.weight\", \"backward_resblocks.main.5.conv.0.bias\", \"backward_resblocks.main.5.conv.2.weight\", \"backward_resblocks.main.5.conv.2.bias\", \"backward_resblocks.main.6.conv.0.weight\", \"backward_resblocks.main.6.conv.0.bias\", \"backward_resblocks.main.6.conv.2.weight\", \"backward_resblocks.main.6.conv.2.bias\", \"backward_resblocks.main.7.conv.0.weight\", \"backward_resblocks.main.7.conv.0.bias\", \"backward_resblocks.main.7.conv.2.weight\", \"backward_resblocks.main.7.conv.2.bias\", \"backward_resblocks.main.8.conv.0.weight\", \"backward_resblocks.main.8.conv.0.bias\", \"backward_resblocks.main.8.conv.2.weight\", \"backward_resblocks.main.8.conv.2.bias\", \"backward_resblocks.main.9.conv.0.weight\", \"backward_resblocks.main.9.conv.0.bias\", \"backward_resblocks.main.9.conv.2.weight\", \"backward_resblocks.main.9.conv.2.bias\", \"backward_resblocks.main.10.conv.0.weight\", \"backward_resblocks.main.10.conv.0.bias\", \"backward_resblocks.main.10.conv.2.weight\", \"backward_resblocks.main.10.conv.2.bias\", \"backward_resblocks.main.11.conv.0.weight\", \"backward_resblocks.main.11.conv.0.bias\", \"backward_resblocks.main.11.conv.2.weight\", \"backward_resblocks.main.11.conv.2.bias\", \"backward_resblocks.main.12.conv.0.weight\", \"backward_resblocks.main.12.conv.0.bias\", \"backward_resblocks.main.12.conv.2.weight\", \"backward_resblocks.main.12.conv.2.bias\", \"backward_resblocks.main.13.conv.0.weight\", \"backward_resblocks.main.13.conv.0.bias\", \"backward_resblocks.main.13.conv.2.weight\", \"backward_resblocks.main.13.conv.2.bias\", \"backward_resblocks.main.14.conv.0.weight\", \"backward_resblocks.main.14.conv.0.bias\", \"backward_resblocks.main.14.conv.2.weight\", \"backward_resblocks.main.14.conv.2.bias\", \"backward_resblocks.main.15.conv.0.weight\", \"backward_resblocks.main.15.conv.0.bias\", \"backward_resblocks.main.15.conv.2.weight\", \"backward_resblocks.main.15.conv.2.bias\", \"backward_resblocks.main.16.conv.0.weight\", \"backward_resblocks.main.16.conv.0.bias\", \"backward_resblocks.main.16.conv.2.weight\", \"backward_resblocks.main.16.conv.2.bias\", \"backward_resblocks.main.17.conv.0.weight\", \"backward_resblocks.main.17.conv.0.bias\", \"backward_resblocks.main.17.conv.2.weight\", \"backward_resblocks.main.17.conv.2.bias\", \"backward_resblocks.main.18.conv.0.weight\", \"backward_resblocks.main.18.conv.0.bias\", \"backward_resblocks.main.18.conv.2.weight\", \"backward_resblocks.main.18.conv.2.bias\", \"backward_resblocks.main.19.conv.0.weight\", \"backward_resblocks.main.19.conv.0.bias\", \"backward_resblocks.main.19.conv.2.weight\", \"backward_resblocks.main.19.conv.2.bias\", \"backward_resblocks.main.20.conv.0.weight\", \"backward_resblocks.main.20.conv.0.bias\", \"backward_resblocks.main.20.conv.2.weight\", \"backward_resblocks.main.20.conv.2.bias\", \"backward_resblocks.main.21.conv.0.weight\", \"backward_resblocks.main.21.conv.0.bias\", \"backward_resblocks.main.21.conv.2.weight\", \"backward_resblocks.main.21.conv.2.bias\", \"backward_resblocks.main.22.conv.0.weight\", \"backward_resblocks.main.22.conv.0.bias\", \"backward_resblocks.main.22.conv.2.weight\", \"backward_resblocks.main.22.conv.2.bias\", \"backward_resblocks.main.23.conv.0.weight\", \"backward_resblocks.main.23.conv.0.bias\", \"backward_resblocks.main.23.conv.2.weight\", \"backward_resblocks.main.23.conv.2.bias\", \"backward_resblocks.main.24.conv.0.weight\", \"backward_resblocks.main.24.conv.0.bias\", \"backward_resblocks.main.24.conv.2.weight\", \"backward_resblocks.main.24.conv.2.bias\", \"backward_resblocks.main.25.conv.0.weight\", \"backward_resblocks.main.25.conv.0.bias\", \"backward_resblocks.main.25.conv.2.weight\", \"backward_resblocks.main.25.conv.2.bias\", \"backward_resblocks.main.26.conv.0.weight\", \"backward_resblocks.main.26.conv.0.bias\", \"backward_resblocks.main.26.conv.2.weight\", \"backward_resblocks.main.26.conv.2.bias\", \"backward_resblocks.main.27.conv.0.weight\", \"backward_resblocks.main.27.conv.0.bias\", \"backward_resblocks.main.27.conv.2.weight\", \"backward_resblocks.main.27.conv.2.bias\", \"backward_resblocks.main.28.conv.0.weight\", \"backward_resblocks.main.28.conv.0.bias\", \"backward_resblocks.main.28.conv.2.weight\", \"backward_resblocks.main.28.conv.2.bias\", \"backward_resblocks.main.29.conv.0.weight\", \"backward_resblocks.main.29.conv.0.bias\", \"backward_resblocks.main.29.conv.2.weight\", \"backward_resblocks.main.29.conv.2.bias\", \"backward_resblocks.main.30.conv.0.weight\", \"backward_resblocks.main.30.conv.0.bias\", \"backward_resblocks.main.30.conv.2.weight\", \"backward_resblocks.main.30.conv.2.bias\", \"backward_resblocks.main.31.conv.0.weight\", \"backward_resblocks.main.31.conv.0.bias\", \"backward_resblocks.main.31.conv.2.weight\", \"backward_resblocks.main.31.conv.2.bias\", \"forward_resblocks.main.2.conv.0.weight\", \"forward_resblocks.main.2.conv.0.bias\", \"forward_resblocks.main.2.conv.2.weight\", \"forward_resblocks.main.2.conv.2.bias\", \"forward_resblocks.main.3.conv.0.weight\", \"forward_resblocks.main.3.conv.0.bias\", \"forward_resblocks.main.3.conv.2.weight\", \"forward_resblocks.main.3.conv.2.bias\", \"forward_resblocks.main.4.conv.0.weight\", \"forward_resblocks.main.4.conv.0.bias\", \"forward_resblocks.main.4.conv.2.weight\", \"forward_resblocks.main.4.conv.2.bias\", \"forward_resblocks.main.5.conv.0.weight\", \"forward_resblocks.main.5.conv.0.bias\", \"forward_resblocks.main.5.conv.2.weight\", \"forward_resblocks.main.5.conv.2.bias\", \"forward_resblocks.main.6.conv.0.weight\", \"forward_resblocks.main.6.conv.0.bias\", \"forward_resblocks.main.6.conv.2.weight\", \"forward_resblocks.main.6.conv.2.bias\", \"forward_resblocks.main.7.conv.0.weight\", \"forward_resblocks.main.7.conv.0.bias\", \"forward_resblocks.main.7.conv.2.weight\", \"forward_resblocks.main.7.conv.2.bias\", \"forward_resblocks.main.8.conv.0.weight\", \"forward_resblocks.main.8.conv.0.bias\", \"forward_resblocks.main.8.conv.2.weight\", \"forward_resblocks.main.8.conv.2.bias\", \"forward_resblocks.main.9.conv.0.weight\", \"forward_resblocks.main.9.conv.0.bias\", \"forward_resblocks.main.9.conv.2.weight\", \"forward_resblocks.main.9.conv.2.bias\", \"forward_resblocks.main.10.conv.0.weight\", \"forward_resblocks.main.10.conv.0.bias\", \"forward_resblocks.main.10.conv.2.weight\", \"forward_resblocks.main.10.conv.2.bias\", \"forward_resblocks.main.11.conv.0.weight\", \"forward_resblocks.main.11.conv.0.bias\", \"forward_resblocks.main.11.conv.2.weight\", \"forward_resblocks.main.11.conv.2.bias\", \"forward_resblocks.main.12.conv.0.weight\", \"forward_resblocks.main.12.conv.0.bias\", \"forward_resblocks.main.12.conv.2.weight\", \"forward_resblocks.main.12.conv.2.bias\", \"forward_resblocks.main.13.conv.0.weight\", \"forward_resblocks.main.13.conv.0.bias\", \"forward_resblocks.main.13.conv.2.weight\", \"forward_resblocks.main.13.conv.2.bias\", \"forward_resblocks.main.14.conv.0.weight\", \"forward_resblocks.main.14.conv.0.bias\", \"forward_resblocks.main.14.conv.2.weight\", \"forward_resblocks.main.14.conv.2.bias\", \"forward_resblocks.main.15.conv.0.weight\", \"forward_resblocks.main.15.conv.0.bias\", \"forward_resblocks.main.15.conv.2.weight\", \"forward_resblocks.main.15.conv.2.bias\", \"forward_resblocks.main.16.conv.0.weight\", \"forward_resblocks.main.16.conv.0.bias\", \"forward_resblocks.main.16.conv.2.weight\", \"forward_resblocks.main.16.conv.2.bias\", \"forward_resblocks.main.17.conv.0.weight\", \"forward_resblocks.main.17.conv.0.bias\", \"forward_resblocks.main.17.conv.2.weight\", \"forward_resblocks.main.17.conv.2.bias\", \"forward_resblocks.main.18.conv.0.weight\", \"forward_resblocks.main.18.conv.0.bias\", \"forward_resblocks.main.18.conv.2.weight\", \"forward_resblocks.main.18.conv.2.bias\", \"forward_resblocks.main.19.conv.0.weight\", \"forward_resblocks.main.19.conv.0.bias\", \"forward_resblocks.main.19.conv.2.weight\", \"forward_resblocks.main.19.conv.2.bias\", \"forward_resblocks.main.20.conv.0.weight\", \"forward_resblocks.main.20.conv.0.bias\", \"forward_resblocks.main.20.conv.2.weight\", \"forward_resblocks.main.20.conv.2.bias\", \"forward_resblocks.main.21.conv.0.weight\", \"forward_resblocks.main.21.conv.0.bias\", \"forward_resblocks.main.21.conv.2.weight\", \"forward_resblocks.main.21.conv.2.bias\", \"forward_resblocks.main.22.conv.0.weight\", \"forward_resblocks.main.22.conv.0.bias\", \"forward_resblocks.main.22.conv.2.weight\", \"forward_resblocks.main.22.conv.2.bias\", \"forward_resblocks.main.23.conv.0.weight\", \"forward_resblocks.main.23.conv.0.bias\", \"forward_resblocks.main.23.conv.2.weight\", \"forward_resblocks.main.23.conv.2.bias\", \"forward_resblocks.main.24.conv.0.weight\", \"forward_resblocks.main.24.conv.0.bias\", \"forward_resblocks.main.24.conv.2.weight\", \"forward_resblocks.main.24.conv.2.bias\", \"forward_resblocks.main.25.conv.0.weight\", \"forward_resblocks.main.25.conv.0.bias\", \"forward_resblocks.main.25.conv.2.weight\", \"forward_resblocks.main.25.conv.2.bias\", \"forward_resblocks.main.26.conv.0.weight\", \"forward_resblocks.main.26.conv.0.bias\", \"forward_resblocks.main.26.conv.2.weight\", \"forward_resblocks.main.26.conv.2.bias\", \"forward_resblocks.main.27.conv.0.weight\", \"forward_resblocks.main.27.conv.0.bias\", \"forward_resblocks.main.27.conv.2.weight\", \"forward_resblocks.main.27.conv.2.bias\", \"forward_resblocks.main.28.conv.0.weight\", \"forward_resblocks.main.28.conv.0.bias\", \"forward_resblocks.main.28.conv.2.weight\", \"forward_resblocks.main.28.conv.2.bias\", \"forward_resblocks.main.29.conv.0.weight\", \"forward_resblocks.main.29.conv.0.bias\", \"forward_resblocks.main.29.conv.2.weight\", \"forward_resblocks.main.29.conv.2.bias\", \"forward_resblocks.main.30.conv.0.weight\", \"forward_resblocks.main.30.conv.0.bias\", \"forward_resblocks.main.30.conv.2.weight\", \"forward_resblocks.main.30.conv.2.bias\", \"forward_resblocks.main.31.conv.0.weight\", \"forward_resblocks.main.31.conv.0.bias\", \"forward_resblocks.main.31.conv.2.weight\", \"forward_resblocks.main.31.conv.2.bias\"]\nu += [\"backward_resblocks.main.2.0.conv1.weight\", \"backward_resblocks.main.2.0.conv1.bias\", \"backward_resblocks.main.2.0.conv2.weight\", \"backward_resblocks.main.2.0.conv2.bias\", \"backward_resblocks.main.2.1.conv1.weight\", \"backward_resblocks.main.2.1.conv1.bias\", \"backward_resblocks.main.2.1.conv2.weight\", \"backward_resblocks.main.2.1.conv2.bias\", \"backward_resblocks.main.2.2.conv1.weight\", \"backward_resblocks.main.2.2.conv1.bias\", \"backward_resblocks.main.2.2.conv2.weight\", \"backward_resblocks.main.2.2.conv2.bias\", \"backward_resblocks.main.2.3.conv1.weight\", \"backward_resblocks.main.2.3.conv1.bias\", \"backward_resblocks.main.2.3.conv2.weight\", \"backward_resblocks.main.2.3.conv2.bias\", \"backward_resblocks.main.2.4.conv1.weight\", \"backward_resblocks.main.2.4.conv1.bias\", \"backward_resblocks.main.2.4.conv2.weight\", \"backward_resblocks.main.2.4.conv2.bias\", \"backward_resblocks.main.2.5.conv1.weight\", \"backward_resblocks.main.2.5.conv1.bias\", \"backward_resblocks.main.2.5.conv2.weight\", \"backward_resblocks.main.2.5.conv2.bias\", \"backward_resblocks.main.2.6.conv1.weight\", \"backward_resblocks.main.2.6.conv1.bias\", \"backward_resblocks.main.2.6.conv2.weight\", \"backward_resblocks.main.2.6.conv2.bias\", \"backward_resblocks.main.2.7.conv1.weight\", \"backward_resblocks.main.2.7.conv1.bias\", \"backward_resblocks.main.2.7.conv2.weight\", \"backward_resblocks.main.2.7.conv2.bias\", \"backward_resblocks.main.2.8.conv1.weight\", \"backward_resblocks.main.2.8.conv1.bias\", \"backward_resblocks.main.2.8.conv2.weight\", \"backward_resblocks.main.2.8.conv2.bias\", \"backward_resblocks.main.2.9.conv1.weight\", \"backward_resblocks.main.2.9.conv1.bias\", \"backward_resblocks.main.2.9.conv2.weight\", \"backward_resblocks.main.2.9.conv2.bias\", \"backward_resblocks.main.2.10.conv1.weight\", \"backward_resblocks.main.2.10.conv1.bias\", \"backward_resblocks.main.2.10.conv2.weight\", \"backward_resblocks.main.2.10.conv2.bias\", \"backward_resblocks.main.2.11.conv1.weight\", \"backward_resblocks.main.2.11.conv1.bias\", \"backward_resblocks.main.2.11.conv2.weight\", \"backward_resblocks.main.2.11.conv2.bias\", \"backward_resblocks.main.2.12.conv1.weight\", \"backward_resblocks.main.2.12.conv1.bias\", \"backward_resblocks.main.2.12.conv2.weight\", \"backward_resblocks.main.2.12.conv2.bias\", \"backward_resblocks.main.2.13.conv1.weight\", \"backward_resblocks.main.2.13.conv1.bias\", \"backward_resblocks.main.2.13.conv2.weight\", \"backward_resblocks.main.2.13.conv2.bias\", \"backward_resblocks.main.2.14.conv1.weight\", \"backward_resblocks.main.2.14.conv1.bias\", \"backward_resblocks.main.2.14.conv2.weight\", \"backward_resblocks.main.2.14.conv2.bias\", \"backward_resblocks.main.2.15.conv1.weight\", \"backward_resblocks.main.2.15.conv1.bias\", \"backward_resblocks.main.2.15.conv2.weight\", \"backward_resblocks.main.2.15.conv2.bias\", \"backward_resblocks.main.2.16.conv1.weight\", \"backward_resblocks.main.2.16.conv1.bias\", \"backward_resblocks.main.2.16.conv2.weight\", \"backward_resblocks.main.2.16.conv2.bias\", \"backward_resblocks.main.2.17.conv1.weight\", \"backward_resblocks.main.2.17.conv1.bias\", \"backward_resblocks.main.2.17.conv2.weight\", \"backward_resblocks.main.2.17.conv2.bias\", \"backward_resblocks.main.2.18.conv1.weight\", \"backward_resblocks.main.2.18.conv1.bias\", \"backward_resblocks.main.2.18.conv2.weight\", \"backward_resblocks.main.2.18.conv2.bias\", \"backward_resblocks.main.2.19.conv1.weight\", \"backward_resblocks.main.2.19.conv1.bias\", \"backward_resblocks.main.2.19.conv2.weight\", \"backward_resblocks.main.2.19.conv2.bias\", \"backward_resblocks.main.2.20.conv1.weight\", \"backward_resblocks.main.2.20.conv1.bias\", \"backward_resblocks.main.2.20.conv2.weight\", \"backward_resblocks.main.2.20.conv2.bias\", \"backward_resblocks.main.2.21.conv1.weight\", \"backward_resblocks.main.2.21.conv1.bias\", \"backward_resblocks.main.2.21.conv2.weight\", \"backward_resblocks.main.2.21.conv2.bias\", \"backward_resblocks.main.2.22.conv1.weight\", \"backward_resblocks.main.2.22.conv1.bias\", \"backward_resblocks.main.2.22.conv2.weight\", \"backward_resblocks.main.2.22.conv2.bias\", \"backward_resblocks.main.2.23.conv1.weight\", \"backward_resblocks.main.2.23.conv1.bias\", \"backward_resblocks.main.2.23.conv2.weight\", \"backward_resblocks.main.2.23.conv2.bias\", \"backward_resblocks.main.2.24.conv1.weight\", \"backward_resblocks.main.2.24.conv1.bias\", \"backward_resblocks.main.2.24.conv2.weight\", \"backward_resblocks.main.2.24.conv2.bias\", \"backward_resblocks.main.2.25.conv1.weight\", \"backward_resblocks.main.2.25.conv1.bias\", \"backward_resblocks.main.2.25.conv2.weight\", \"backward_resblocks.main.2.25.conv2.bias\", \"backward_resblocks.main.2.26.conv1.weight\", \"backward_resblocks.main.2.26.conv1.bias\", \"backward_resblocks.main.2.26.conv2.weight\", \"backward_resblocks.main.2.26.conv2.bias\", \"backward_resblocks.main.2.27.conv1.weight\", \"backward_resblocks.main.2.27.conv1.bias\", \"backward_resblocks.main.2.27.conv2.weight\", \"backward_resblocks.main.2.27.conv2.bias\", \"backward_resblocks.main.2.28.conv1.weight\", \"backward_resblocks.main.2.28.conv1.bias\", \"backward_resblocks.main.2.28.conv2.weight\", \"backward_resblocks.main.2.28.conv2.bias\", \"backward_resblocks.main.2.29.conv1.weight\", \"backward_resblocks.main.2.29.conv1.bias\", \"backward_resblocks.main.2.29.conv2.weight\", \"backward_resblocks.main.2.29.conv2.bias\", \"forward_resblocks.main.2.0.conv1.weight\", \"forward_resblocks.main.2.0.conv1.bias\", \"forward_resblocks.main.2.0.conv2.weight\", \"forward_resblocks.main.2.0.conv2.bias\", \"forward_resblocks.main.2.1.conv1.weight\", \"forward_resblocks.main.2.1.conv1.bias\", \"forward_resblocks.main.2.1.conv2.weight\", \"forward_resblocks.main.2.1.conv2.bias\", \"forward_resblocks.main.2.2.conv1.weight\", \"forward_resblocks.main.2.2.conv1.bias\", \"forward_resblocks.main.2.2.conv2.weight\", \"forward_resblocks.main.2.2.conv2.bias\", \"forward_resblocks.main.2.3.conv1.weight\", \"forward_resblocks.main.2.3.conv1.bias\", \"forward_resblocks.main.2.3.conv2.weight\", \"forward_resblocks.main.2.3.conv2.bias\", \"forward_resblocks.main.2.4.conv1.weight\", \"forward_resblocks.main.2.4.conv1.bias\", \"forward_resblocks.main.2.4.conv2.weight\", \"forward_resblocks.main.2.4.conv2.bias\", \"forward_resblocks.main.2.5.conv1.weight\", \"forward_resblocks.main.2.5.conv1.bias\", \"forward_resblocks.main.2.5.conv2.weight\", \"forward_resblocks.main.2.5.conv2.bias\", \"forward_resblocks.main.2.6.conv1.weight\", \"forward_resblocks.main.2.6.conv1.bias\", \"forward_resblocks.main.2.6.conv2.weight\", \"forward_resblocks.main.2.6.conv2.bias\", \"forward_resblocks.main.2.7.conv1.weight\", \"forward_resblocks.main.2.7.conv1.bias\", \"forward_resblocks.main.2.7.conv2.weight\", \"forward_resblocks.main.2.7.conv2.bias\", \"forward_resblocks.main.2.8.conv1.weight\", \"forward_resblocks.main.2.8.conv1.bias\", \"forward_resblocks.main.2.8.conv2.weight\", \"forward_resblocks.main.2.8.conv2.bias\", \"forward_resblocks.main.2.9.conv1.weight\", \"forward_resblocks.main.2.9.conv1.bias\", \"forward_resblocks.main.2.9.conv2.weight\", \"forward_resblocks.main.2.9.conv2.bias\", \"forward_resblocks.main.2.10.conv1.weight\", \"forward_resblocks.main.2.10.conv1.bias\", \"forward_resblocks.main.2.10.conv2.weight\", \"forward_resblocks.main.2.10.conv2.bias\", \"forward_resblocks.main.2.11.conv1.weight\", \"forward_resblocks.main.2.11.conv1.bias\", \"forward_resblocks.main.2.11.conv2.weight\", \"forward_resblocks.main.2.11.conv2.bias\", \"forward_resblocks.main.2.12.conv1.weight\", \"forward_resblocks.main.2.12.conv1.bias\", \"forward_resblocks.main.2.12.conv2.weight\", \"forward_resblocks.main.2.12.conv2.bias\", \"forward_resblocks.main.2.13.conv1.weight\", \"forward_resblocks.main.2.13.conv1.bias\", \"forward_resblocks.main.2.13.conv2.weight\", \"forward_resblocks.main.2.13.conv2.bias\", \"forward_resblocks.main.2.14.conv1.weight\", \"forward_resblocks.main.2.14.conv1.bias\", \"forward_resblocks.main.2.14.conv2.weight\", \"forward_resblocks.main.2.14.conv2.bias\", \"forward_resblocks.main.2.15.conv1.weight\", \"forward_resblocks.main.2.15.conv1.bias\", \"forward_resblocks.main.2.15.conv2.weight\", \"forward_resblocks.main.2.15.conv2.bias\", \"forward_resblocks.main.2.16.conv1.weight\", \"forward_resblocks.main.2.16.conv1.bias\", \"forward_resblocks.main.2.16.conv2.weight\", \"forward_resblocks.main.2.16.conv2.bias\", \"forward_resblocks.main.2.17.conv1.weight\", \"forward_resblocks.main.2.17.conv1.bias\", \"forward_resblocks.main.2.17.conv2.weight\", \"forward_resblocks.main.2.17.conv2.bias\", \"forward_resblocks.main.2.18.conv1.weight\", \"forward_resblocks.main.2.18.conv1.bias\", \"forward_resblocks.main.2.18.conv2.weight\", \"forward_resblocks.main.2.18.conv2.bias\", \"forward_resblocks.main.2.19.conv1.weight\", \"forward_resblocks.main.2.19.conv1.bias\", \"forward_resblocks.main.2.19.conv2.weight\", \"forward_resblocks.main.2.19.conv2.bias\", \"forward_resblocks.main.2.20.conv1.weight\", \"forward_resblocks.main.2.20.conv1.bias\", \"forward_resblocks.main.2.20.conv2.weight\", \"forward_resblocks.main.2.20.conv2.bias\", \"forward_resblocks.main.2.21.conv1.weight\", \"forward_resblocks.main.2.21.conv1.bias\", \"forward_resblocks.main.2.21.conv2.weight\", \"forward_resblocks.main.2.21.conv2.bias\", \"forward_resblocks.main.2.22.conv1.weight\", \"forward_resblocks.main.2.22.conv1.bias\", \"forward_resblocks.main.2.22.conv2.weight\", \"forward_resblocks.main.2.22.conv2.bias\", \"forward_resblocks.main.2.23.conv1.weight\", \"forward_resblocks.main.2.23.conv1.bias\", \"forward_resblocks.main.2.23.conv2.weight\", \"forward_resblocks.main.2.23.conv2.bias\", \"forward_resblocks.main.2.24.conv1.weight\", \"forward_resblocks.main.2.24.conv1.bias\", \"forward_resblocks.main.2.24.conv2.weight\", \"forward_resblocks.main.2.24.conv2.bias\", \"forward_resblocks.main.2.25.conv1.weight\", \"forward_resblocks.main.2.25.conv1.bias\", \"forward_resblocks.main.2.25.conv2.weight\", \"forward_resblocks.main.2.25.conv2.bias\", \"forward_resblocks.main.2.26.conv1.weight\", \"forward_resblocks.main.2.26.conv1.bias\", \"forward_resblocks.main.2.26.conv2.weight\", \"forward_resblocks.main.2.26.conv2.bias\", \"forward_resblocks.main.2.27.conv1.weight\", \"forward_resblocks.main.2.27.conv1.bias\", \"forward_resblocks.main.2.27.conv2.weight\", \"forward_resblocks.main.2.27.conv2.bias\", \"forward_resblocks.main.2.28.conv1.weight\", \"forward_resblocks.main.2.28.conv1.bias\", \"forward_resblocks.main.2.28.conv2.weight\", \"forward_resblocks.main.2.28.conv2.bias\", \"forward_resblocks.main.2.29.conv1.weight\", \"forward_resblocks.main.2.29.conv1.bias\", \"forward_resblocks.main.2.29.conv2.weight\", \"forward_resblocks.main.2.29.conv2.bias\"]\n# BasicVSRNet\nm += [\"upsample.0.weight\", \"upsample.0.bias\", \"upsample.2.main.0.weight\", \"upsample.2.main.0.bias\", \"upsample.4.main.0.weight\", \"upsample.4.main.0.bias\", \"upsample.6.weight\", \"upsample.6.bias\", \"upsample.8.weight\", \"upsample.8.bias\"]\nu += [\"fusion.weight\", \"fusion.bias\", \"upsample1.main.0.weight\", \"upsample1.main.0.bias\", \"upsample2.main.0.weight\", \"upsample2.main.0.bias\", \"conv_hr.weight\", \"conv_hr.bias\", \"conv_last.weight\", \"conv_last.bias\"]\n\nfor mk, uk in zip(m, u):\n new[mk] = new.pop(uk)\n\n\n# Remove\nu = list()\n# SPyNet\nu += [\"spynet.mean\", \"spynet.std\", \"spynet.basic_module.0.basic_module.0.conv.weight\", \"spynet.basic_module.0.basic_module.0.conv.bias\", \"spynet.basic_module.0.basic_module.1.conv.weight\", \"spynet.basic_module.0.basic_module.1.conv.bias\", \"spynet.basic_module.0.basic_module.2.conv.weight\", \"spynet.basic_module.0.basic_module.2.conv.bias\", \"spynet.basic_module.0.basic_module.3.conv.weight\", \"spynet.basic_module.0.basic_module.3.conv.bias\", \"spynet.basic_module.0.basic_module.4.conv.weight\", \"spynet.basic_module.0.basic_module.4.conv.bias\", \"spynet.basic_module.1.basic_module.0.conv.weight\", \"spynet.basic_module.1.basic_module.0.conv.bias\", \"spynet.basic_module.1.basic_module.1.conv.weight\", \"spynet.basic_module.1.basic_module.1.conv.bias\", \"spynet.basic_module.1.basic_module.2.conv.weight\", \"spynet.basic_module.1.basic_module.2.conv.bias\", \"spynet.basic_module.1.basic_module.3.conv.weight\", \"spynet.basic_module.1.basic_module.3.conv.bias\", \"spynet.basic_module.1.basic_module.4.conv.weight\", \"spynet.basic_module.1.basic_module.4.conv.bias\", \"spynet.basic_module.2.basic_module.0.conv.weight\", \"spynet.basic_module.2.basic_module.0.conv.bias\", \"spynet.basic_module.2.basic_module.1.conv.weight\", \"spynet.basic_module.2.basic_module.1.conv.bias\", \"spynet.basic_module.2.basic_module.2.conv.weight\", \"spynet.basic_module.2.basic_module.2.conv.bias\", \"spynet.basic_module.2.basic_module.3.conv.weight\", \"spynet.basic_module.2.basic_module.3.conv.bias\", \"spynet.basic_module.2.basic_module.4.conv.weight\", \"spynet.basic_module.2.basic_module.4.conv.bias\", \"spynet.basic_module.3.basic_module.0.conv.weight\", \"spynet.basic_module.3.basic_module.0.conv.bias\", \"spynet.basic_module.3.basic_module.1.conv.weight\", \"spynet.basic_module.3.basic_module.1.conv.bias\", \"spynet.basic_module.3.basic_module.2.conv.weight\", \"spynet.basic_module.3.basic_module.2.conv.bias\", \"spynet.basic_module.3.basic_module.3.conv.weight\", \"spynet.basic_module.3.basic_module.3.conv.bias\", \"spynet.basic_module.3.basic_module.4.conv.weight\", \"spynet.basic_module.3.basic_module.4.conv.bias\", \"spynet.basic_module.4.basic_module.0.conv.weight\", \"spynet.basic_module.4.basic_module.0.conv.bias\", \"spynet.basic_module.4.basic_module.1.conv.weight\", \"spynet.basic_module.4.basic_module.1.conv.bias\", \"spynet.basic_module.4.basic_module.2.conv.weight\", \"spynet.basic_module.4.basic_module.2.conv.bias\", \"spynet.basic_module.4.basic_module.3.conv.weight\", \"spynet.basic_module.4.basic_module.3.conv.bias\", \"spynet.basic_module.4.basic_module.4.conv.weight\", \"spynet.basic_module.4.basic_module.4.conv.bias\", \"spynet.basic_module.5.basic_module.0.conv.weight\", \"spynet.basic_module.5.basic_module.0.conv.bias\", \"spynet.basic_module.5.basic_module.1.conv.weight\", \"spynet.basic_module.5.basic_module.1.conv.bias\", \"spynet.basic_module.5.basic_module.2.conv.weight\", \"spynet.basic_module.5.basic_module.2.conv.bias\", \"spynet.basic_module.5.basic_module.3.conv.weight\", \"spynet.basic_module.5.basic_module.3.conv.bias\", \"spynet.basic_module.5.basic_module.4.conv.weight\", \"spynet.basic_module.5.basic_module.4.conv.bias\"]\n\nfor u_ in u:\n new.pop(u_)\n\n# Save\n# torch.save(new, '/Users/ibobby/Dataset/model_weights/BasicVSR/v-bi-fixed.pth')\nprint('model_fixed')\n"
] | [
[
"torch.load"
]
] |
scottma/aws-batch-monte-carlo-workshop | [
"52e14f1e2ee287b91dbc15abdb2fb55c7fef4693"
] | [
"src/simulator.py"
] | [
"'''\nver 0.1, namera@ , initial-release, Oct26'17\nver 0.2, namera@ , included execution id for traceability, Nov3'17\nver 0.3, shawo@ , Corrected typos in variable names, Apr23'18\nver 0.4, angelaw@ , Added S3 upload flag, removed risk calculations, Oct17'18\n\n\nHedge Your Own Funds: Running Monte Carlo Simulations on AWS Batch\n=================================================================\n\nThis worker script launches the Monte-Carlo simulations.\nAll input parameters have defaults, please see 'parser.add_argument' for details or simply append -h at the end of the execution line to\nsee input parameter details.\n\ne.g. python simulator.py -h\n\nOutput:\n-------\nThis script writes simualted results into CSV files, the files are:\n<exec_id>_<Stock_Name>_MonteCarloSimResult.csv - for example, AMZN_MonteCarloSimResult.csv , this file holds the last Monte-Carlo simulated value\n for each iteration and the expected cache value given the trading strategy specified in the notebook. Initial investment is $100,000\nportfolioRiskAssessment.csv - returns the risk value of multiple-socks portfolio. see --portfolio_stocks_list input paramter for more detai$\n\n\nSample executions:\n------------------\nRun simulation with default parameters:\npython simulator.py\n\nSpecify 1,000,000 simulations to execute:\npython simulator.py --iterations 1000000\n'''\n\nimport pandas as pd\nfrom pandas_datareader import data as pdr\nimport numpy as np\nimport datetime, time\nfrom math import sqrt\n# from scipy.stats import norm\n#import fix_yahoo_finance as yf\nimport yfinance as yf\nimport boto3\nimport uuid\nimport subprocess\n\nimport argparse\n\ns3 = boto3.client('s3')\n\n\n# Save the simulation results to an S3 bucket\ndef saveToS3(bucket_name, filename, STOCK):\n if bucket_name is not None:\n s3.upload_file(filename, bucket_name, \"simulation-results/stock=\" + STOCK + \"/\" + filename)\n print(\"Finished uploading \" + filename + \"to s3.\")\n subprocess.check_output(['rm', filename])\n else:\n print(\"skipping s3 upload as no bucket is specified\")\n\n\ndef setup_cmd_parser():\n parser = argparse.ArgumentParser(description='Running Monte Carlo Simulations for stock purchases.')\n parser.add_argument('--iterations', dest='iterations', default=100, type=int,\n help='Number of simulated iterations default=100')\n parser.add_argument('--stock', dest='stock', default=\"AMZN\",\n help='Stock Name')\n parser.add_argument('--short_window_days', dest='short_window_days', default=10, type=int,\n help='Short moving avearge in days default=10')\n parser.add_argument('--long_window_days', dest='long_window_days', default=40, type=int,\n help='Long moving avearge in days (default=40)')\n parser.add_argument('--trading_days', dest='trading_days', default=252, type=int,\n help='Number of trading days (default=252)')\n parser.add_argument('--s3_bucket', dest='s3_bucket', default=None,\n help='S3 bucket to upload results to. If not provided, the results will not be uploaded to S3.')\n return parser\n\n\ndef run_simulations(parser):\n args = parser.parse_args()\n\n STOCK = args.stock\n short_window = args.short_window_days\n long_window = args.long_window_days\n trading_days = args.trading_days\n sim_num = args.iterations\n print(\"running \" + str(sim_num) + \" iterations\")\n # portfolio_stocks_list = args.stocks_list\n s3_bucket = args.s3_bucket\n\n # create output files (CSV) unique string to preapend\n # if (file_prepend_str == 'None'):\n # t = time.localtime()\n # file_prepend_str = time.strftime('%b-%d-%Y_%H%M', t)\n t = time.localtime()\n file_prepend_str = time.strftime('%b-%d-%Y_%H%M%S', t)\n\n # Import stock information to dataframe. ADDED 04/2018 - Fix for yahoo finance\n yf.pdr_override()\n stock_df = pdr.get_data_yahoo(STOCK, start=datetime.datetime(2006, 10, 1), end=datetime.datetime(2017, 10, 1))\n\n # Calculate the compound annual growth rate (CAGR) which\n # will give us our mean return input (mu)\n days = (stock_df.index[-1] - stock_df.index[0]).days\n cagr = ((((stock_df['Adj Close'][-1]) / stock_df['Adj Close'][1])) ** (365.0 / days)) - 1\n mu = cagr\n\n # create a series of percentage returns and calculate\n # the annual volatility of returns. Generally, the higher the volatility,\n # the riskier the investment in that stock, which results in investing in one over another.\n stock_df['Returns'] = stock_df['Adj Close'].pct_change()\n vol = stock_df['Returns'].std() * sqrt(252)\n\n # Set the initial capital\n initial_capital = float(100000.0)\n\n # Set up empty list to hold our ending values for each simulated price series\n sim_result = []\n\n # Set up empty list to hold portfolio value for each simulated price serries, this is the value of position['total']\n portfolio_total = []\n\n # Define Variables\n start_price = stock_df['Adj Close'][-1] # starting stock price (i.e. last available real stock price)\n\n # Initialize the `signals` DataFrame\n signals = pd.DataFrame()\n\n # Initialize by setting the value for all rows in this column to 0.0.\n signals['signal'] = 0.0\n signals['short_mavg'] = 0.0\n\n # Create a DataFrame `positions`\n positions = pd.DataFrame(index=signals.index).fillna(0.0)\n\n # Choose number of runs to simulate - I have chosen 1,000\n for i in range(sim_num):\n # create list of daily returns using random normal distribution\n daily_returns = np.random.normal(mu / trading_days, vol / sqrt(trading_days), trading_days) + 1\n\n # Set starting price and create price series generated by above random daily returns\n price_list = [start_price]\n\n for x in daily_returns:\n price_list.append(price_list[-1] * x)\n\n # Convert list to Pandas DataFrame\n price_list_df = pd.DataFrame(price_list)\n\n # Append the ending value of each simulated run to the empty list we created at the beginning\n sim_result.append(price_list[-1])\n\n # Create short simple moving average over the short & long window\n signals['short_mavg'] = price_list_df[0].rolling(short_window).mean()\n signals['long_mavg'] = price_list_df[0].rolling(long_window).mean()\n\n # Create a signal when the short moving average crosses the long moving average,\n # but only for the period greater than the shortest moving average window.\n signals['signal'][short_window:] = np.where(signals['short_mavg'][short_window:]\n > signals['long_mavg'][short_window:], 1.0, 0.0)\n\n # Generate trading orders\n signals['positions'] = signals['signal'].diff()\n\n # Buy 100 shares\n positions[STOCK] = 100 * signals['signal']\n\n # Initialize the portfolio with value owned\n portfolio = positions.multiply(price_list_df[0], axis=0)\n\n # Store the difference in shares owned\n pos_diff = positions.diff()\n\n # Add `holdings` to portfolio\n portfolio['holdings'] = (positions.multiply(price_list_df[0], axis=0)).sum(axis=1)\n\n # Add `cash` to portfolio\n portfolio['cash'] = initial_capital - (pos_diff.multiply(price_list_df[0], axis=0)).sum(axis=1).cumsum()\n\n # Add `total` to portfolio\n portfolio['total'] = portfolio['cash'] + portfolio['holdings']\n\n # Append the ending value of each simulated run to the empty list we created at the beginning\n portfolio_total.append(portfolio['total'].iloc[-1])\n\n # Simulation Results\n # print sim_result\n df1 = pd.DataFrame(sim_result, columns=[\"MonteCarloResults\"])\n\n # Portfolio Total\n # Print portfolio_total\n df2 = pd.DataFrame(portfolio_total, columns=[\"portfolioTotal\"])\n\n # Create one data frame and write to file.\n result = pd.concat([df1, df2], axis=1)\n result.reset_index(inplace=True, drop=True) \n joined_result_file = file_prepend_str + \"_\" + STOCK + \"_\" + (str(uuid.uuid4()))[:6] + \"_MonteCarloSimResult.csv\"\n result.to_csv(joined_result_file)\n saveToS3(s3_bucket, joined_result_file, STOCK)\n\n\nif __name__ == \"__main__\":\n parser = setup_cmd_parser()\n run_simulations(parser)\n"
] | [
[
"numpy.where",
"pandas.DataFrame",
"pandas.concat"
]
] |
openalgorithmdevelopers/MATSS-Original | [
"76b9cc7a23fd83b0cca0249addcccabd9bb8bf92"
] | [
"generate_OPENSMILE_features_csv.py"
] | [
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Sep 28 17:46:55 2021\r\n\r\n@author: bhupendra.singh\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom tqdm import tqdm\r\nimport opensmile\r\n\r\n\r\ntotalSubjects = 21\r\ntotalUtterances = 60 #the number of utterances of words in a folder for every subject\r\nfeatureName = \"mfcc\"\r\nfeatures_length = 6373\r\n\r\n#utterancesFolder = \".//WebBasedTest/word_level_utterances\"\r\nutterancesFolder = \".//WebBasedTest/word_level_utterances_manual\"\r\nfeaturesFolder = \".//WebBasedTest/features_files\"\r\n\r\navialableSubjectList = list(range(totalSubjects))\r\navialableSubjectList = [x+1 for x in avialableSubjectList] # adding 1 to all the itesms since the subject folder starts from 1 and not 0\r\n#avialableSubjectList.remove(4)\r\n\r\ntotalUtterancesList = list(range(totalUtterances))\r\ntotalUtterancesList = [x+1 for x in totalUtterancesList] # adding 1 to all the itesms since the subject folder starts from 1 and not 0\r\n\r\nfeatures_set = np.zeros((len(totalUtterancesList), features_length))\r\nfs = 48000 #i found it to be this value, change it as per your information\r\n\r\nfor currentSubjectNo in tqdm(avialableSubjectList): # iterate for all the available subjects\r\n #currentSubjectNo += 1\r\n print(\"Current Subject = \" + str(currentSubjectNo))\r\n \r\n for currentUtteranceNo in totalUtterancesList: #iterate for for all the utterances\r\n #print(\"Current Subject = \" + str(currentUtteranceNo))\r\n #utteranceFileName = utterancesFolder + \"/utterances_subject_\" + str(currentSubjectNo) + \"/utterance\" + str(currentUtteranceNo) + \".wav\"\r\n utteranceFileName = utterancesFolder + \"/utterances_subject_\" + str(currentSubjectNo) + \"/\" + str(currentUtteranceNo) + \".wav\"\r\n #print(fileName)\r\n #sound_file = AudioSegment.from_wav(utteranceFileName)\r\n #mfcc_features = mfcc(np.array(sound_file.get_array_of_samples()), fs)\r\n smile = opensmile.Smile(\r\n feature_set=opensmile.FeatureSet.ComParE_2016,\r\n feature_level=opensmile.FeatureLevel.Functionals,\r\n )\r\n y = smile.process_file(utteranceFileName)\r\n #mfcc_features.resize(128) #standardizing the size\r\n y = y.to_numpy()\r\n #y = y[0,:]\r\n #y = y.resize(6372) #standardizing the size\r\n features_set[currentUtteranceNo - 1, :] = y\r\n \r\n df = pd.DataFrame(features_set)\r\n featuresFileName = featuresFolder + \"/Subject\" + str(currentSubjectNo) + \"_\" + featureName + \".csv\"\r\n df.to_csv(featuresFileName)"
] | [
[
"pandas.DataFrame"
]
] |
TobyLing/Comparative-Study-of-Deep-Learning-Models-for-Segmentation-of-Corpus-Callosum | [
"c1840440c29e1bcc6fac3830003b026d7f452513"
] | [
"networks/resnet34.py"
] | [
"import torch\n\nfrom torchvision import models\n\nfrom tensorboardX import SummaryWriter\n\nwriter = SummaryWriter()\n\nresnet = models.resnet34(pretrained=True)\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nmodel = resnet.to(device)\n\ndummy_input = torch.zeros(8, 3,512,512)\n\nwriter.add_graph(model, dummy_input, False)\nwriter.close()\n\n\n\n"
] | [
[
"torch.zeros",
"torch.cuda.is_available"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.