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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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. RETURN_STATUS_UNEXPECTED("Requested shape has an invalid element count!");
  143. }
  144. // If there was any unknown dimensions, then update the requested shape to fill in the unknown
  145. // dimension with the correct value. If there were no unknown dim's then the output shape will
  146. // remain to be the same as the requested shape.
  147. if (unknown_dim_position != TensorShape::kDimUnknown) {
  148. requested_shape[unknown_dim_position] = (num_elements / num_elements_of_shape);
  149. }
  150. // Any unknown dimension is filled in now. Set the output shape
  151. *out_shape = TensorShape(requested_shape);
  152. return Status::OK();
  153. }
  154. // getter function for the shape
  155. TensorShape ColDescriptor::shape() const {
  156. if (tensor_shape_ != nullptr) {
  157. return *tensor_shape_; // copy construct a shape to return
  158. } else {
  159. return TensorShape::CreateUnknownRankShape(); // empty shape to return
  160. }
  161. }
  162. const char DataSchema::DEFAULT_DATA_SCHEMA_FILENAME[] = "datasetSchema.json";
  163. // Constructor 1: Simple constructor that leaves things uninitialized.
  164. DataSchema::DataSchema() : num_rows_(0) {}
  165. // Internal helper function. Parses the json schema file in any order and produces a schema that
  166. // does not follow any particular order (json standard does not enforce any ordering protocol).
  167. // This one produces a schema that contains all of the columns from the schema file.
  168. Status DataSchema::AnyOrderLoad(nlohmann::json column_tree) {
  169. // Iterate over the json file. Each parent json node is the column name,
  170. // followed by the column properties in the child tree under the column.
  171. // Outer loop here iterates over the parents (i.e. the column name)
  172. if (!column_tree.is_array()) {
  173. for (nlohmann::json::iterator it = column_tree.begin(); it != column_tree.end(); ++it) {
  174. std::string col_name = it.key();
  175. nlohmann::json column_child_tree = it.value();
  176. RETURN_IF_NOT_OK(ColumnLoad(column_child_tree, col_name));
  177. }
  178. } else {
  179. // Case where the schema is a list of columns not a dict
  180. for (nlohmann::json::iterator it = column_tree.begin(); it != column_tree.end(); ++it) {
  181. nlohmann::json column_child_tree = it.value();
  182. RETURN_IF_NOT_OK(ColumnLoad(column_child_tree, ""));
  183. }
  184. }
  185. return Status::OK();
  186. }
  187. // Internal helper function. For each input column name, perform a lookup to the json document to
  188. // find the matching column. When the match is found, process that column to build the column
  189. // descriptor and add to the schema in the order in which the input column names are given.id
  190. Status DataSchema::ColumnOrderLoad(nlohmann::json column_tree, const std::vector<std::string> &columns_to_load) {
  191. if (!column_tree.is_array()) {
  192. // the json file is dict (e.g., {image: ...})
  193. // Loop over the column name list
  194. for (const auto &curr_col_name : columns_to_load) {
  195. // Find the column in the json document
  196. auto column_info = column_tree.find(common::SafeCStr(curr_col_name));
  197. if (column_info == column_tree.end()) {
  198. RETURN_STATUS_UNEXPECTED("Invalid data, failed to find column name: " + curr_col_name);
  199. }
  200. // At this point, columnInfo.value() is the subtree in the json document that contains
  201. // all of the data for a given column. This data will formulate our schema column.
  202. const std::string &col_name = column_info.key();
  203. nlohmann::json column_child_tree = column_info.value();
  204. RETURN_IF_NOT_OK(ColumnLoad(column_child_tree, col_name));
  205. }
  206. } else {
  207. // the json file is array (e.g., [name: image...])
  208. // Loop over the column name list
  209. for (const auto &curr_col_name : columns_to_load) {
  210. // Find the column in the json document
  211. int32_t index = -1;
  212. int32_t i = 0;
  213. for (const auto &it_child : column_tree.items()) {
  214. auto name = it_child.value().find("name");
  215. if (name == it_child.value().end()) {
  216. RETURN_STATUS_UNEXPECTED("Name field is missing for this column.");
  217. }
  218. if (name.value() == curr_col_name) {
  219. index = i;
  220. break;
  221. }
  222. i++;
  223. }
  224. if (index == -1) {
  225. RETURN_STATUS_UNEXPECTED("Invalid data, failed to find column name: " + curr_col_name);
  226. }
  227. nlohmann::json column_child_tree = column_tree[index];
  228. RETURN_IF_NOT_OK(ColumnLoad(column_child_tree, curr_col_name));
  229. }
  230. }
  231. return Status::OK();
  232. }
  233. // Internal helper function for parsing shape info and building a vector for the shape construction.
  234. static Status buildShape(const nlohmann::json &shapeVal, std::vector<dsize_t> *outShape) {
  235. if (outShape == nullptr) {
  236. RETURN_STATUS_UNEXPECTED("null output shape");
  237. }
  238. if (shapeVal.empty()) return Status::OK();
  239. // Iterate over the integer list and add those values to the output shape tensor
  240. auto items = shapeVal.items();
  241. using it_type = decltype(items.begin());
  242. (void)std::transform(items.begin(), items.end(), std::back_inserter(*outShape), [](it_type j) { return j.value(); });
  243. return Status::OK();
  244. }
  245. // Internal helper function. Given the json tree for a given column, load it into our schema.
  246. Status DataSchema::ColumnLoad(nlohmann::json column_child_tree, const std::string &col_name) {
  247. int32_t rank_value = -1;
  248. TensorImpl t_impl_value = TensorImpl::kFlexible;
  249. std::string name, type_str;
  250. std::vector<dsize_t> tmp_shape = {};
  251. bool shape_field_exists = false;
  252. // Iterate over this column's attributes.
  253. // Manually iterating each of the child nodes/trees here so that we can provide our own error handling.
  254. for (const auto &it_child : column_child_tree.items()) {
  255. // Save the data for each of the attributes into variables. We'll use these to construct later.
  256. if (it_child.key() == "name") {
  257. name = it_child.value();
  258. } else if (it_child.key() == "type") {
  259. type_str = it_child.value();
  260. } else if (it_child.key() == "rank") {
  261. rank_value = it_child.value();
  262. } else if (it_child.key() == "t_impl") {
  263. STR_TO_TENSORIMPL(it_child.value(), t_impl_value);
  264. } else if (it_child.key() == "shape") {
  265. shape_field_exists = true;
  266. RETURN_IF_NOT_OK(buildShape(it_child.value(), &tmp_shape));
  267. } else {
  268. std::string err_msg = "Unexpected column attribute " + it_child.key() + " for column " + col_name;
  269. RETURN_STATUS_UNEXPECTED(err_msg);
  270. }
  271. }
  272. if (!name.empty()) {
  273. if (!col_name.empty() && col_name != name) {
  274. std::string err_msg =
  275. "json schema file for column " + col_name + " has column name that does not match columnsToLoad";
  276. RETURN_STATUS_UNEXPECTED(err_msg);
  277. }
  278. } else {
  279. if (col_name.empty()) {
  280. std::string err_msg = "json schema file for column " + col_name + " has invalid or missing column name.";
  281. RETURN_STATUS_UNEXPECTED(err_msg);
  282. } else {
  283. name = col_name;
  284. }
  285. }
  286. // data type is mandatory field
  287. if (type_str.empty())
  288. return Status(StatusCode::kMDUnexpectedError, __LINE__, __FILE__,
  289. "json schema file for column " + col_name + " has invalid or missing column type.");
  290. // rank number is mandatory field
  291. if (rank_value <= -1)
  292. return Status(StatusCode::kMDUnexpectedError, __LINE__, __FILE__,
  293. "json schema file for column " + col_name + " must define a positive rank value.");
  294. // Create the column descriptor for this column from the data we pulled from the json file
  295. TensorShape col_shape = TensorShape(tmp_shape);
  296. if (shape_field_exists)
  297. (void)this->AddColumn(ColDescriptor(name, DataType(type_str), t_impl_value, rank_value, &col_shape));
  298. else
  299. // Create a column descriptor that doesn't have a shape
  300. (void)this->AddColumn(ColDescriptor(name, DataType(type_str), t_impl_value, rank_value));
  301. return Status::OK();
  302. }
  303. // Parses a schema json file and populates the columns and meta info.
  304. Status DataSchema::LoadSchemaFile(const std::string &schema_file_path,
  305. const std::vector<std::string> &columns_to_load) {
  306. try {
  307. std::ifstream in(schema_file_path);
  308. nlohmann::json js;
  309. in >> js;
  310. RETURN_IF_NOT_OK(PreLoadExceptionCheck(js));
  311. try {
  312. num_rows_ = js.at("numRows").get<int64_t>();
  313. } catch (nlohmann::json::out_of_range &e) {
  314. num_rows_ = 0;
  315. } catch (nlohmann::json::exception &e) {
  316. RETURN_STATUS_UNEXPECTED("Unable to parse \"numRows\" from schema");
  317. }
  318. nlohmann::json column_tree = js.at("columns");
  319. if (column_tree.empty()) {
  320. RETURN_STATUS_UNEXPECTED("columns is null");
  321. }
  322. if (columns_to_load.empty()) {
  323. // Parse the json tree and load the schema's columns in whatever order that the json
  324. // layout decides
  325. RETURN_IF_NOT_OK(this->AnyOrderLoad(column_tree));
  326. } else {
  327. RETURN_IF_NOT_OK(this->ColumnOrderLoad(column_tree, columns_to_load));
  328. }
  329. } catch (const std::exception &err) {
  330. // Catch any exception and convert to Status return code
  331. RETURN_STATUS_UNEXPECTED("Schema file failed to load");
  332. }
  333. return Status::OK();
  334. }
  335. // Parses a schema json string and populates the columns and meta info.
  336. Status DataSchema::LoadSchemaString(const std::string &schema_json_string,
  337. const std::vector<std::string> &columns_to_load) {
  338. try {
  339. nlohmann::json js = nlohmann::json::parse(schema_json_string);
  340. RETURN_IF_NOT_OK(PreLoadExceptionCheck(js));
  341. num_rows_ = js.value("numRows", 0);
  342. nlohmann::json column_tree = js.at("columns");
  343. if (column_tree.empty()) {
  344. RETURN_STATUS_UNEXPECTED("columns is null");
  345. }
  346. if (columns_to_load.empty()) {
  347. // Parse the json tree and load the schema's columns in whatever order that the json
  348. // layout decides
  349. RETURN_IF_NOT_OK(this->AnyOrderLoad(column_tree));
  350. } else {
  351. RETURN_IF_NOT_OK(this->ColumnOrderLoad(column_tree, columns_to_load));
  352. }
  353. } catch (const std::exception &err) {
  354. // Catch any exception and convert to Status return code
  355. RETURN_STATUS_UNEXPECTED("Schema file failed to load");
  356. }
  357. return Status::OK();
  358. }
  359. // Destructor
  360. DataSchema::~DataSchema() = default;
  361. // Getter for the ColDescriptor by index
  362. const ColDescriptor &DataSchema::column(int32_t idx) const {
  363. MS_ASSERT(idx < static_cast<int>(col_descs_.size()));
  364. return col_descs_[idx];
  365. }
  366. // A print method typically used for debugging
  367. void DataSchema::Print(std::ostream &out) const {
  368. out << "Dataset schema: (";
  369. for (const auto &col_desc : col_descs_) {
  370. out << col_desc << "\n";
  371. }
  372. }
  373. // Adds a column descriptor to the schema
  374. Status DataSchema::AddColumn(const ColDescriptor &cd) {
  375. // Sanity check there's not a duplicate name before adding the column
  376. for (int32_t i = 0; i < col_descs_.size(); ++i) {
  377. if (col_descs_[i].name() == cd.name()) {
  378. std::ostringstream ss;
  379. ss << "column name '" << cd.name() << "' already exists in schema.";
  380. std::string err_msg = ss.str();
  381. RETURN_STATUS_UNEXPECTED(err_msg);
  382. }
  383. }
  384. col_descs_.push_back(cd);
  385. return Status::OK();
  386. }
  387. // Internal helper function. Performs sanity checks on the json file setup.
  388. Status DataSchema::PreLoadExceptionCheck(const nlohmann::json &js) {
  389. // Check if columns node exists. It is required for building schema from file.
  390. if (js.find("columns") == js.end())
  391. return Status(StatusCode::kMDUnexpectedError, __LINE__, __FILE__,
  392. "\"columns\" node is required in the schema json file.");
  393. return Status::OK();
  394. }
  395. // Loops through all columns in the schema and returns a map with the column
  396. // name to column index number.
  397. Status DataSchema::GetColumnNameMap(std::unordered_map<std::string, int32_t> *out_column_name_map) {
  398. if (out_column_name_map == nullptr) {
  399. return Status(StatusCode::kMDUnexpectedError, __LINE__, __FILE__, "unexpected null output column name map.");
  400. }
  401. for (int32_t i = 0; i < col_descs_.size(); ++i) {
  402. if (col_descs_[i].name().empty()) {
  403. return Status(StatusCode::kMDUnexpectedError, __LINE__, __FILE__,
  404. "Constructing column name map from schema, but found empty column name.");
  405. }
  406. (*out_column_name_map)[col_descs_[i].name()] = i;
  407. }
  408. return Status::OK();
  409. }
  410. } // namespace dataset
  411. } // namespace mindspore