UNPKG

@mindconnect/mindconnect-nodejs

Version:

NodeJS Library for MindSphere Connectivity - TypeScript SDK for MindSphere - MindSphere Command Line Interface - MindSphere Development Proxy

205 lines 12.3 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const console_1 = require("console"); const fs = require("fs"); const _ = require("lodash"); const path = require("path"); const utils_1 = require("../../api/utils"); const command_utils_1 = require("./command-utils"); let color = (0, command_utils_1.getColor)("blue"); exports.default = (program) => { program .command("trend-prediction") .alias("tp") .option("-f, --file <timeseries>", `timeseries file`, `timeseries-sample.mdsp.json`) .option("-m, --mode [train|predict|trainandpredict|list|read|delete]", `mode see ${color("@ Additional Documentation")}`, "list") .option("-o, --output <output>", `output variables`) .option("-i, --input <input>", `input variables (comma separated)`) .option("-e, --modelid <modelid>", `modelid of the stored model for prediction`) .option("-r, --predict <predict>", `regression parameters for prediction (comma separated)`) .option("-c, --predictfile <predictfile>", `regression parameters for prediction as timeseries`) .option("-d, --degree [degree]", "degree for linear / polynomial regression ", "1") .option("-y, --retry <number>", "retry attempts before giving up", "3") .option("-p, --passkey <passkey>", `passkey`) .option("-v, --verbose", "verbose output") .description(`${color("perform trend prediction (linear/polynomial) @")}`) .action((options) => { (() => __awaiter(void 0, void 0, void 0, function* () { try { checkRequiredParameters(options); const sdk = (0, command_utils_1.getSdk)(options); color = (0, command_utils_1.adjustColor)(color, options, true); (0, command_utils_1.homeDirLog)(options.verbose, color); (0, command_utils_1.proxyLog)(options.verbose, color); const trendPrediction = sdk.GetTrendPredictionClient(); switch (options.mode) { case "list": yield listModels(trendPrediction, options); break; case "get": const model = yield (0, utils_1.retry)(options.retry, () => trendPrediction.GetModel(options.modelid)); console.log(JSON.stringify(model, null, 2)); console.log(`Sucessfully retrieved model with ${color(options.modelid)} id.`); break; case "delete": yield (0, utils_1.retry)(options.retry, () => trendPrediction.DeleteModel(options.modelid)); console.log(`Sucessfully deleted model with ${color(options.modelid)} id`); break; case "train": { const trainBody = getTrainBody(options); const trainedModel = yield (0, utils_1.retry)(options.retry, () => trendPrediction.Train(trainBody)); (0, command_utils_1.verboseLog)(JSON.stringify(trainedModel, null, 2), options.verbose); console.log(`Sucessfully trained model with ${color(trainedModel.id)} id.`); } break; case "predict": { const predictionData = getpredictors(options); const prediction = (yield (0, utils_1.retry)(options.retry, () => trendPrediction.Predict(Object.assign({ modelConfiguration: { modelId: options.modelid } }, predictionData)))); displayPrediction(options, prediction); } break; case "trainandpredict": { const trainBody = getTrainBody(options); const predictionData = getpredictors(options); const prediction = (yield (0, utils_1.retry)(options.retry, () => trendPrediction.TrainAndPredict(Object.assign(Object.assign({}, trainBody), predictionData)))); displayPrediction(options, prediction); } break; } } catch (err) { (0, command_utils_1.errorLog)(err, options.verbose); } }))(); }) .on("--help", () => { (0, console_1.log)("\n Examples:\n"); (0, console_1.log)(` mc trend-prediction --mode list \t\t\t\t lists all trend prediction models`); (0, console_1.log)(` mc trend-prediction --mode get --modelid 12345..ef \t\t retrieves the trend prediction model from the mindsphere`); (0, console_1.log)(` mc trend-prediction --mode delete --modelid 12345..ef \t deletes the trend prediction model from the mindsphere`); (0, console_1.log)(` mc tp --mode trendandpredict \t\t\t\t training and prediction in one single step (see parameters below)`); (0, console_1.log)(`\n mc tp --mode train -f data.json -i "temp,vibration" -o "quality" -d 2 \t\t trains quadratic fit function for f(temp, vibration) = quality `); (0, console_1.log)(` mc tp --mode predict --modelid 12345..ef -i "temp,vibration" -o "quality" -p "30,0.01" predict the quality with temp=30, vibration=0.01 using trained model`); (0, console_1.log)("\n Additional Documentation:\n"); (0, console_1.log)(` ${color("https://developer.mindsphere.io/apis/analytics-trendprediction/api-trendprediction-basics.html")}`); (0, command_utils_1.serviceCredentialLog)(color); }); }; function displayPrediction(options, prediction) { options.predict && console.log(`${color("(")}${options.input}${color(") =>")} ${options.output}`); const predictionValue = prediction[0].timeSeries[0][options.output]; options.predict && console.log(`${color("(")}${options.predict}${color(") =>")} ${predictionValue}`); options.predictfile ? console.log(JSON.stringify(prediction, null, 2)) : (0, command_utils_1.verboseLog)(JSON.stringify(prediction, null, 2), options.verbose); } function getpredictors(options) { const predictiondata = { predictionData: [ { variable: { entityId: "cli-trend-prediction", propertySetName: "cli-trend-prediction" }, timeSeries: [{ _time: new Date().toISOString() }], }, ], }; if (options.predictfile) { const predictorsPath = path.resolve(options.predictfile); const predictorData = fs.readFileSync(predictorsPath); const timeseries = JSON.parse(predictorData.toString()); predictiondata.predictionData[0].timeSeries = timeseries; } else { const variables = `${options.input}`.split(",").map((x) => x.trim()); const predictors = `${options.predict}`.split(",").map((x) => x.trim()); for (let i = 0; i < variables.length; i++) { const element = variables[i]; predictiondata.predictionData[0].timeSeries[0][element] = predictors[i]; } } return predictiondata; } function getTrainBody(options) { const timeSeriesDataFile = path.resolve(options.file); (0, command_utils_1.verboseLog)(`reading data from ${timeSeriesDataFile}`, options.verbose); const buffer = fs.readFileSync(timeSeriesDataFile); const data = JSON.parse(buffer.toString()); const variables = `${options.input}`.split(",").map((x) => x.trim()); const allvariables = [...variables, options.output, "_time"]; const result = _.map(data, (item) => _.pick(item, allvariables)); const params = { modelConfiguration: { polynomialDegree: options.degree }, metadataConfiguration: { outputVariable: { entityId: "cli-trend-prediction", propertySetName: "cli-trend-prediction", propertyName: options.output, }, inputVariables: [], }, trainingData: [ { variable: { entityId: "cli-trend-prediction", propertySetName: "cli-trend-prediction" }, timeSeries: result, }, ], }; variables.forEach((item) => { params.metadataConfiguration.inputVariables.push({ entityId: "cli-trend-prediction", propertySetName: "cli-trend-prediction", propertyName: item, }); }); return params; } function listModels(trendPrediction, options) { return __awaiter(this, void 0, void 0, function* () { const result = (yield (0, utils_1.retry)(options.retry, () => trendPrediction.GetModels())); console.log(`${color("id")} function creation date`); result.forEach((element) => { var _a, _b, _c, _d; console.log(`${color(element.id)} ${color("(")}${(_b = (_a = element.metadataConfiguration) === null || _a === void 0 ? void 0 : _a.inputVariables) === null || _b === void 0 ? void 0 : _b.map((x) => x.propertyName).join(",")}${color(") =>")} ${(_d = (_c = element.metadataConfiguration) === null || _c === void 0 ? void 0 : _c.outputVariable) === null || _d === void 0 ? void 0 : _d.propertyName} ${element.creationDate}`); }); }); } function checkRequiredParameters(options) { !options.mode && (0, command_utils_1.errorLog)("You have to provide the mode for the command. Run mc tp --help for full syntax and examples.", true); !["train", "predict", "trainandpredict", "list", "get", "delete"].includes(options.mode) && (0, command_utils_1.errorLog)(`the mode must be either one of: ${color("train, predict or trainandpredict")} for trend prediction or ${color("list, get, delete")} for model management`, true); options.mode === "get" && !options.modelid && (0, command_utils_1.errorLog)("you have to specify the id of the model (--modelid)", true); options.mode === "delete" && !options.modelid && (0, command_utils_1.errorLog)("you have to specify the id of the model (--modelid)", true); (options.mode === "train" || options.mode === "trainandpredict") && !options.file && (0, command_utils_1.errorLog)("you have to provide the file with timeseries data (--file)", true); (options.mode === "train" || options.mode === "trainandpredict") && !options.degree && (0, command_utils_1.errorLog)("you have to provide the polynomial degree for the fit function (--degree)", true); (options.mode === "train" || options.mode === "predict" || options.mode === "trainandpredict") && !options.input && (0, command_utils_1.errorLog)("you have to provide the input variables for the fit function (--input)", true); (options.mode === "train" || options.mode === "predict" || options.mode === "trainandpredict") && !options.output && (0, command_utils_1.errorLog)("you have to provide the output variable for the fit function (--output)", true); options.mode === "predict" && !options.modelid && (0, command_utils_1.errorLog)("you have to specify the id of the model (--modelid)", true); (options.mode === "predict" || options.mode === "trainandpredict") && !(options.predict ? !options.predictfile : options.predictfile) && (0, command_utils_1.errorLog)("you have to provide the values of input variables (--predict) or (--predictfile) (but not both)", true); } //# sourceMappingURL=trend-prediction.js.map