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 20 kB

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