You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

data_schema.cc 19 kB

6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. /**
  2. * Copyright 2019 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "minddata/dataset/engine/data_schema.h"
  17. #include <algorithm>
  18. #include <fstream>
  19. #include <iostream>
  20. #include <map>
  21. #include <memory>
  22. #include <sstream>
  23. #include <nlohmann/json.hpp>
  24. #include "utils/ms_utils.h"
  25. #include "minddata/dataset/util/status.h"
  26. #include "minddata/dataset/core/tensor_shape.h"
  27. #ifndef ENABLE_ANDROID
  28. #include "utils/log_adapter.h"
  29. #else
  30. #include "mindspore/lite/src/common/log_adapter.h"
  31. #endif
  32. namespace mindspore {
  33. namespace dataset {
  34. // A macro for converting an input string representing the column type to it's actual
  35. // numeric column type.
  36. #define STR_TO_TENSORIMPL(in_col_str, out_type) \
  37. do { \
  38. if (in_col_str == "cvmat") { \
  39. out_type = TensorImpl::kCv; \
  40. } else if (in_col_str == "flex") { \
  41. out_type = TensorImpl::kFlexible; \
  42. } else if (in_col_str == "np") { \
  43. out_type = TensorImpl::kNP; \
  44. } else { \
  45. out_type = TensorImpl::kNone; \
  46. } \
  47. } while (false)
  48. // Constructor 1: Simple constructor that leaves things uninitialized.
  49. ColDescriptor::ColDescriptor()
  50. : type_(DataType::DE_UNKNOWN), rank_(0), tensor_impl_(TensorImpl::kNone), tensor_shape_(nullptr) {}
  51. // Constructor 2: Main constructor
  52. ColDescriptor::ColDescriptor(const std::string &col_name, DataType col_type, TensorImpl tensor_impl, int32_t rank,
  53. const TensorShape *in_shape)
  54. : type_(col_type), rank_(rank), tensor_impl_(tensor_impl), col_name_(col_name) {
  55. // If a shape was provided, create unique pointer for it and copy construct it into
  56. // our shape. Otherwise, set our shape to be empty.
  57. if (in_shape != nullptr) {
  58. // Create a shape and copy construct it into our column's shape.
  59. tensor_shape_ = std::make_unique<TensorShape>(*in_shape);
  60. } else {
  61. tensor_shape_ = nullptr;
  62. }
  63. // If the user input a shape, then the rank of the input shape needs to match
  64. // the input rank
  65. if (in_shape != nullptr && in_shape->known() && in_shape->Size() != rank_) {
  66. rank_ = in_shape->Size();
  67. MS_LOG(WARNING) << "Rank does not match the number of dimensions in the provided shape."
  68. << " Overriding rank with the number of dimensions in the provided shape.";
  69. }
  70. }
  71. // Explicit copy constructor is required
  72. ColDescriptor::ColDescriptor(const ColDescriptor &in_cd)
  73. : type_(in_cd.type_), rank_(in_cd.rank_), tensor_impl_(in_cd.tensor_impl_), col_name_(in_cd.col_name_) {
  74. // If it has a tensor shape, make a copy of it with our own unique_ptr.
  75. tensor_shape_ = in_cd.hasShape() ? std::make_unique<TensorShape>(in_cd.shape()) : nullptr;
  76. }
  77. // Assignment overload
  78. ColDescriptor &ColDescriptor::operator=(const ColDescriptor &in_cd) {
  79. if (&in_cd != this) {
  80. type_ = in_cd.type_;
  81. rank_ = in_cd.rank_;
  82. tensor_impl_ = in_cd.tensor_impl_;
  83. col_name_ = in_cd.col_name_;
  84. // If it has a tensor shape, make a copy of it with our own unique_ptr.
  85. tensor_shape_ = in_cd.hasShape() ? std::make_unique<TensorShape>(in_cd.shape()) : nullptr;
  86. }
  87. return *this;
  88. }
  89. // Destructor
  90. ColDescriptor::~ColDescriptor() = default;
  91. // A print method typically used for debugging
  92. void ColDescriptor::Print(std::ostream &out) const {
  93. out << " Name : " << col_name_ << "\n Type : " << type_ << "\n Rank : " << rank_
  94. << "\n Shape : (";
  95. if (tensor_shape_) {
  96. out << *tensor_shape_ << ")\n";
  97. } else {
  98. out << "no shape provided)\n";
  99. }
  100. }
  101. // Given a number of elements, this function will compute what the actual Tensor shape would be.
  102. // If there is no starting TensorShape in this column, or if there is a shape but it contains
  103. // an unknown dimension, then the output shape returned shall resolve dimensions as needed.
  104. Status ColDescriptor::MaterializeTensorShape(int32_t num_elements, TensorShape *out_shape) const {
  105. if (out_shape == nullptr) {
  106. RETURN_STATUS_UNEXPECTED("Unexpected null output shape argument.");
  107. }
  108. // If the shape is not given in this column, then we assume the shape will be: {numElements}
  109. if (tensor_shape_ == nullptr) {
  110. if (this->rank() == 0 && num_elements == 1) {
  111. *out_shape = TensorShape::CreateScalar();
  112. return Status::OK();
  113. }
  114. *out_shape = TensorShape({num_elements});
  115. return Status::OK();
  116. }
  117. // Build the real TensorShape based on the requested shape and the number of elements in the data.
  118. // If there are unknown dimensions, then the unknown dimension needs to be filled in.
  119. // Example: requestedShape: {?,4,3}.
  120. // If numElements is 24, then the output shape can be computed to: {2,4,3}
  121. std::vector<dsize_t> requested_shape = tensor_shape_->AsVector();
  122. int64_t num_elements_of_shape = 1; // init to 1 as a starting multiplier.
  123. // unknownDimPosition variable is overloaded to provide 2 meanings:
  124. // 1) If it's set to DIM_UNKNOWN, then it provides a boolean knowledge to tell us if there are
  125. // any unknown dimensions. i.e. if it's set to unknown, then there are no unknown dimensions.
  126. // 2) If it's set to a numeric value, then this is the vector index position within the shape
  127. // where the single unknown dimension can be found.
  128. int64_t unknown_dim_position = TensorShape::kDimUnknown; // Assume there are no unknown dims to start
  129. for (int i = 0; i < requested_shape.size(); ++i) {
  130. // If we already had an unknown dimension, then we cannot have a second unknown dimension.
  131. // We only support the compute of a single unknown dim.
  132. if (requested_shape[i] == TensorShape::kDimUnknown && unknown_dim_position != TensorShape::kDimUnknown) {
  133. return Status(StatusCode::kUnexpectedError, __LINE__, __FILE__,
  134. "Requested shape has more than one unknown dimension!");
  135. }
  136. // If the current dimension in the requested shape is a known value, then compute the number of
  137. // elements so far.
  138. if (requested_shape[i] != TensorShape::kDimUnknown) {
  139. num_elements_of_shape *= requested_shape[i];
  140. } else {
  141. // This dimension is unknown so track which dimension position has it.
  142. unknown_dim_position = i;
  143. }
  144. }
  145. // Sanity check the the computed element counts divide evenly into the input element count
  146. if (num_elements < num_elements_of_shape || num_elements_of_shape == 0 || num_elements % num_elements_of_shape != 0) {
  147. RETURN_STATUS_UNEXPECTED("Requested shape has an invalid element count!");
  148. }
  149. // If there was any unknown dimensions, then update the requested shape to fill in the unknown
  150. // dimension with the correct value. If there were no unknown dim's then the output shape will
  151. // remain to be the same as the requested shape.
  152. if (unknown_dim_position != TensorShape::kDimUnknown) {
  153. requested_shape[unknown_dim_position] = (num_elements / num_elements_of_shape);
  154. }
  155. // Any unknown dimension is filled in now. Set the output shape
  156. *out_shape = TensorShape(requested_shape);
  157. return Status::OK();
  158. }
  159. // getter function for the shape
  160. TensorShape ColDescriptor::shape() const {
  161. if (tensor_shape_ != nullptr) {
  162. return *tensor_shape_; // copy construct a shape to return
  163. } else {
  164. return TensorShape::CreateUnknownRankShape(); // empty shape to return
  165. }
  166. }
  167. const char DataSchema::DEFAULT_DATA_SCHEMA_FILENAME[] = "datasetSchema.json";
  168. // Constructor 1: Simple constructor that leaves things uninitialized.
  169. DataSchema::DataSchema() : num_rows_(0) {}
  170. // Internal helper function. Parses the json schema file in any order and produces a schema that
  171. // does not follow any particular order (json standard does not enforce any ordering protocol).
  172. // This one produces a schema that contains all of the columns from the schema file.
  173. Status DataSchema::AnyOrderLoad(nlohmann::json column_tree) {
  174. // Iterate over the json file. Each parent json node is the column name,
  175. // followed by the column properties in the child tree under the column.
  176. // Outer loop here iterates over the parents (i.e. the column name)
  177. if (!column_tree.is_array()) {
  178. for (nlohmann::json::iterator it = column_tree.begin(); it != column_tree.end(); ++it) {
  179. std::string col_name = it.key();
  180. nlohmann::json column_child_tree = it.value();
  181. RETURN_IF_NOT_OK(ColumnLoad(column_child_tree, col_name));
  182. }
  183. } else {
  184. // Case where the schema is a list of columns not a dict
  185. for (nlohmann::json::iterator it = column_tree.begin(); it != column_tree.end(); ++it) {
  186. nlohmann::json column_child_tree = it.value();
  187. RETURN_IF_NOT_OK(ColumnLoad(column_child_tree, ""));
  188. }
  189. }
  190. return Status::OK();
  191. }
  192. // Internal helper function. For each input column name, perform a lookup to the json document to
  193. // find the matching column. When the match is found, process that column to build the column
  194. // descriptor and add to the schema in the order in which the input column names are given.id
  195. Status DataSchema::ColumnOrderLoad(nlohmann::json column_tree, const std::vector<std::string> &columns_to_load) {
  196. if (!column_tree.is_array()) {
  197. // the json file is dict (e.g., {image: ...})
  198. // Loop over the column name list
  199. for (const auto &curr_col_name : columns_to_load) {
  200. // Find the column in the json document
  201. auto column_info = column_tree.find(common::SafeCStr(curr_col_name));
  202. if (column_info == column_tree.end()) {
  203. RETURN_STATUS_UNEXPECTED("Failed to find column " + curr_col_name);
  204. }
  205. // At this point, columnInfo.value() is the subtree in the json document that contains
  206. // all of the data for a given column. This data will formulate our schema column.
  207. const std::string &col_name = column_info.key();
  208. nlohmann::json column_child_tree = column_info.value();
  209. RETURN_IF_NOT_OK(ColumnLoad(column_child_tree, col_name));
  210. }
  211. } else {
  212. // the json file is array (e.g., [name: image...])
  213. // Loop over the column name list
  214. for (const auto &curr_col_name : columns_to_load) {
  215. // Find the column in the json document
  216. int32_t index = -1;
  217. int32_t i = 0;
  218. for (const auto &it_child : column_tree.items()) {
  219. auto name = it_child.value().find("name");
  220. if (name == it_child.value().end()) {
  221. RETURN_STATUS_UNEXPECTED("Name field is missing for this column.");
  222. }
  223. if (name.value() == curr_col_name) {
  224. index = i;
  225. break;
  226. }
  227. i++;
  228. }
  229. if (index == -1) {
  230. RETURN_STATUS_UNEXPECTED("Failed to find column " + curr_col_name);
  231. }
  232. nlohmann::json column_child_tree = column_tree[index];
  233. RETURN_IF_NOT_OK(ColumnLoad(column_child_tree, curr_col_name));
  234. }
  235. }
  236. return Status::OK();
  237. }
  238. // Internal helper function for parsing shape info and building a vector for the shape construction.
  239. static Status buildShape(const nlohmann::json &shapeVal, std::vector<dsize_t> *outShape) {
  240. if (outShape == nullptr) {
  241. RETURN_STATUS_UNEXPECTED("null output shape");
  242. }
  243. if (shapeVal.empty()) return Status::OK();
  244. // Iterate over the integer list and add those values to the output shape tensor
  245. auto items = shapeVal.items();
  246. using it_type = decltype(items.begin());
  247. (void)std::transform(items.begin(), items.end(), std::back_inserter(*outShape), [](it_type j) { return j.value(); });
  248. return Status::OK();
  249. }
  250. // Internal helper function. Given the json tree for a given column, load it into our schema.
  251. Status DataSchema::ColumnLoad(nlohmann::json column_child_tree, const std::string &col_name) {
  252. int32_t rank_value = -1;
  253. TensorImpl t_impl_value = TensorImpl::kFlexible;
  254. std::string name, type_str;
  255. std::vector<dsize_t> tmp_shape = {};
  256. bool shape_field_exists = false;
  257. // Iterate over this column's attributes.
  258. // Manually iterating each of the child nodes/trees here so that we can provide our own error handling.
  259. for (const auto &it_child : column_child_tree.items()) {
  260. // Save the data for each of the attributes into variables. We'll use these to construct later.
  261. if (it_child.key() == "name") {
  262. name = it_child.value();
  263. } else if (it_child.key() == "type") {
  264. type_str = it_child.value();
  265. } else if (it_child.key() == "rank") {
  266. rank_value = it_child.value();
  267. } else if (it_child.key() == "t_impl") {
  268. STR_TO_TENSORIMPL(it_child.value(), t_impl_value);
  269. } else if (it_child.key() == "shape") {
  270. shape_field_exists = true;
  271. RETURN_IF_NOT_OK(buildShape(it_child.value(), &tmp_shape));
  272. } else {
  273. std::string err_msg = "Unexpected column attribute " + it_child.key() + " for column " + col_name;
  274. RETURN_STATUS_UNEXPECTED(err_msg);
  275. }
  276. }
  277. if (!name.empty()) {
  278. if (!col_name.empty() && col_name != name) {
  279. std::string err_msg =
  280. "json schema file for column " + col_name + " has column name that does not match columnsToLoad";
  281. RETURN_STATUS_UNEXPECTED(err_msg);
  282. }
  283. } else {
  284. if (col_name.empty()) {
  285. std::string err_msg = "json schema file for column " + col_name + " has invalid or missing column name.";
  286. RETURN_STATUS_UNEXPECTED(err_msg);
  287. } else {
  288. name = col_name;
  289. }
  290. }
  291. // data type is mandatory field
  292. if (type_str.empty())
  293. return Status(StatusCode::kUnexpectedError, __LINE__, __FILE__,
  294. "json schema file for column " + col_name + " has invalid or missing column type.");
  295. // rank number is mandatory field
  296. if (rank_value <= -1)
  297. return Status(StatusCode::kUnexpectedError, __LINE__, __FILE__,
  298. "json schema file for column " + col_name + " must define a positive rank value.");
  299. // Create the column descriptor for this column from the data we pulled from the json file
  300. TensorShape col_shape = TensorShape(tmp_shape);
  301. if (shape_field_exists)
  302. (void)this->AddColumn(ColDescriptor(name, DataType(type_str), t_impl_value, rank_value, &col_shape));
  303. else
  304. // Create a column descriptor that doesn't have a shape
  305. (void)this->AddColumn(ColDescriptor(name, DataType(type_str), t_impl_value, rank_value));
  306. return Status::OK();
  307. }
  308. // Parses a schema json file and populates the columns and meta info.
  309. Status DataSchema::LoadSchemaFile(const std::string &schema_file_path,
  310. const std::vector<std::string> &columns_to_load) {
  311. try {
  312. std::ifstream in(schema_file_path);
  313. nlohmann::json js;
  314. in >> js;
  315. RETURN_IF_NOT_OK(PreLoadExceptionCheck(js));
  316. try {
  317. num_rows_ = js.at("numRows").get<int64_t>();
  318. } catch (nlohmann::json::out_of_range &e) {
  319. num_rows_ = 0;
  320. } catch (nlohmann::json::exception &e) {
  321. RETURN_STATUS_UNEXPECTED("Unable to parse \"numRows\" from schema");
  322. }
  323. nlohmann::json column_tree = js.at("columns");
  324. if (column_tree.empty()) {
  325. RETURN_STATUS_UNEXPECTED("columns is null");
  326. }
  327. if (columns_to_load.empty()) {
  328. // Parse the json tree and load the schema's columns in whatever order that the json
  329. // layout decides
  330. RETURN_IF_NOT_OK(this->AnyOrderLoad(column_tree));
  331. } else {
  332. RETURN_IF_NOT_OK(this->ColumnOrderLoad(column_tree, columns_to_load));
  333. }
  334. } catch (const std::exception &err) {
  335. // Catch any exception and convert to Status return code
  336. RETURN_STATUS_UNEXPECTED("Schema file failed to load");
  337. }
  338. return Status::OK();
  339. }
  340. // Parses a schema json string and populates the columns and meta info.
  341. Status DataSchema::LoadSchemaString(const std::string &schema_json_string,
  342. const std::vector<std::string> &columns_to_load) {
  343. try {
  344. nlohmann::json js = nlohmann::json::parse(schema_json_string);
  345. RETURN_IF_NOT_OK(PreLoadExceptionCheck(js));
  346. num_rows_ = js.value("numRows", 0);
  347. nlohmann::json column_tree = js.at("columns");
  348. if (column_tree.empty()) {
  349. RETURN_STATUS_UNEXPECTED("columns is null");
  350. }
  351. if (columns_to_load.empty()) {
  352. // Parse the json tree and load the schema's columns in whatever order that the json
  353. // layout decides
  354. RETURN_IF_NOT_OK(this->AnyOrderLoad(column_tree));
  355. } else {
  356. RETURN_IF_NOT_OK(this->ColumnOrderLoad(column_tree, columns_to_load));
  357. }
  358. } catch (const std::exception &err) {
  359. // Catch any exception and convert to Status return code
  360. RETURN_STATUS_UNEXPECTED("Schema file failed to load");
  361. }
  362. return Status::OK();
  363. }
  364. // Destructor
  365. DataSchema::~DataSchema() = default;
  366. // Getter for the ColDescriptor by index
  367. const ColDescriptor &DataSchema::column(int32_t idx) const {
  368. MS_ASSERT(idx < static_cast<int>(col_descs_.size()));
  369. return col_descs_[idx];
  370. }
  371. // A print method typically used for debugging
  372. void DataSchema::Print(std::ostream &out) const {
  373. out << "Dataset schema: (";
  374. for (const auto &col_desc : col_descs_) {
  375. out << col_desc << "\n";
  376. }
  377. }
  378. // Adds a column descriptor to the schema
  379. Status DataSchema::AddColumn(const ColDescriptor &cd) {
  380. // Sanity check there's not a duplicate name before adding the column
  381. for (int32_t i = 0; i < col_descs_.size(); ++i) {
  382. if (col_descs_[i].name() == cd.name()) {
  383. std::ostringstream ss;
  384. ss << "column name '" << cd.name() << "' already exists in schema.";
  385. std::string err_msg = ss.str();
  386. RETURN_STATUS_UNEXPECTED(err_msg);
  387. }
  388. }
  389. col_descs_.push_back(cd);
  390. return Status::OK();
  391. }
  392. // Internal helper function. Performs sanity checks on the json file setup.
  393. Status DataSchema::PreLoadExceptionCheck(const nlohmann::json &js) {
  394. // Check if columns node exists. It is required for building schema from file.
  395. if (js.find("columns") == js.end())
  396. return Status(StatusCode::kUnexpectedError, __LINE__, __FILE__,
  397. "\"columns\" node is required in the schema json file.");
  398. return Status::OK();
  399. }
  400. // Loops through all columns in the schema and returns a map with the column
  401. // name to column index number.
  402. Status DataSchema::GetColumnNameMap(std::unordered_map<std::string, int32_t> *out_column_name_map) {
  403. if (out_column_name_map == nullptr) {
  404. return Status(StatusCode::kUnexpectedError, __LINE__, __FILE__, "unexpected null output column name map.");
  405. }
  406. for (int32_t i = 0; i < col_descs_.size(); ++i) {
  407. if (col_descs_[i].name().empty()) {
  408. return Status(StatusCode::kUnexpectedError, __LINE__, __FILE__,
  409. "Constructing column name map from schema, but found empty column name.");
  410. }
  411. (*out_column_name_map)[col_descs_[i].name()] = i;
  412. }
  413. return Status::OK();
  414. }
  415. } // namespace dataset
  416. } // namespace mindspore