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

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